user3167973 - 1 year ago 51

Java Question

What integer should be returned when we reverse all bits of integer 1? How do we do that with Java code?

No java built in functions should be used. Shouldn't use String reverse, converting to string etc. Only bitwise operations allowed.

`import java.util.*;`

import java.lang.*;

import java.io.*;

class BitReverseInt

{

public static void main (String[] args) throws java.lang.Exception{

System.out.println(reverser(1));

}

public static int reverser(int given){

int input = given;

int temp = 0;

int output = 0;

while(input > 0){

output = output << 1;

temp = input & 1;

input = input >> 1;

output = output | temp;

}

return output;

}

}

Answer Source

You can use a do while loop like this:

```
public static int reverse(int number){
int reverse = 0;
int remainder = 0;
do{
remainder = number%10;
reverse = reverse*10 + remainder;
number = number/10;
}while(number > 0);
return reverse;
}
```

And for bitwise operation: here it goes:

```
int number;
int i = 0, hexadecimal, rev = 0, bit;
while (i++ < NUM_BITS_INT)
{
bit = hexadecimal & 1;
hexadecimal = hexadecimal >> 1;
rev = rev ^ bit;
if (i < NUM_BITS_INT)
rev = rev << 1;
}
System.out.println(rev);
```