Home >Java >javaTutorial >Reverse the actual bits of a given number in Java
Given a non-negative integer n. The goal is to invert n's bits and report the resulting number. When inverting bits, the actual binary form of the integer is used; leading 0s are not considered.
Input − 13
Output − Reverse the given number 11 The actual bits
(13)<sub>10</sub> = (1101)<sub>2</sub>. After reversing the bits, we get: (1011)<sub>2</sub> = (11)<sub>10</sub>.
Explanation − gets the binary bits from the input number, then inverts it and finally converts it to decimal format, which is returned as the output.
Input − 18
Output − Reverse the actual digits of the given number 9.
(18)<sub>10</sub> = (10010)<sub>2</sub>. After reversing the bits, we get: (1001)<sub>2</sub> = (9)<sub>10</sub>.
Explanation − The binary bits are taken from the input number, then inverted and finally converted to decimal format, which is returned as the output.
Inside the main method
Enter the number and pass it to the method reverseBinaryBits(int input)
In methodreverseBinaryBits(int input) Inside
Initialize the variable rev_input to store the reversed bits
The loop iterates until the input is greater than 0 (we start traversing from the right)
Use A bit-right shift operation is used to retrieve each bit in the binary representation of n bit by bit, and a bit-left shift operation is used to accumulate them into rev
class TutorialsPoint{ public static int reverseBinaryBits(int input){ int rev_input = 0; while (input > 0){ rev_input <<= 1; if ((int) (input & 1) == 1){ rev_input ^= 1; } input >>= 1; } return rev_input; } public static void main(String[] args){ int input = 13; System.out.println("Reverse actual bits of the given number"); System.out.println(reverseBinaryBits(input)); } }
If we run the above code it will generate the following output
Reverse actual bits of the given number 11
The above is the detailed content of Reverse the actual bits of a given number in Java. For more information, please follow other related articles on the PHP Chinese website!