I am solving LeetCode 190. Reverse Bits problem:
Reverse bits of a given 32 bits unsigned integer.
Sample test cases:
Example 1:
Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100
represents the unsigned integer 43261596
, so return 964176192
which its binary representation is 00111001011110000010100101000000
.
Example 2:
Input: n = 11111111111111111111111111111101
Output: 3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101
represents the unsigned integer 4294967293
, so return 3221225471
which its binary representation is 10111111111111111111111111111111
.
My solution:
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int last = 0,i,sign = 0;
int sum = 0;
for (i = 0; i < 32; i ){
sum = sum<<1 n&1;
n = n>>1;
}
return sum;
}
}
Here is what I am doing in my solution: right shifting the existing sum and adding the anding with n to it. Finally left shifting the n. These both operations as a whole are reversing the bits. But it doesn't pass the test cases:
Input 00000010100101000001111010011100
Output 0 (00000000000000000000000000000000)
Expected 964176192 (00111001011110000010100101000000)
What am I doing wrong?
CodePudding user response:
Be careful with operations priority, you are doing wrong in sum = sum<<1 n&1
line, it should be
sum = (sum << 1) (n & 1);
note parenthesis which are required here; your original code is equal to sum = sum << (1 n) & 1;
. Let me brush up your code, you don't want last
, sign
etc.:
public class Solution {
public int reverseBits(int n) {
int sum = 0;
for (int i = 0; i < 32; i, n >>= 1)
sum = (sum << 1) (n & 1);
return sum;
}
}