LeetCode#190: Reverse Bits
阿新 • • 發佈:2018-11-19
Description
Reverse bits of a given 32 bits unsigned integer.
Example
Input: 43261596
Output: 964176192
Explanation: 43261596 represented in binary as 00000010100101000001111010011100,
return 964176192 represented in binary as 00111001011110000010100101000000.
Solution
我們把要翻轉的數n
從低位到高位依次放入res
中,放入的方式就是判斷此時n
的最低位是0還是1,如果是1就將res++
n
右移一位,使高一位成為最低位以做下一次的判斷,而每次放入前都將res
左移,使低位的數隨著迴圈都移到了高位。通過這種將原本的低位移動到高位的方式,實現了題目所要求的翻轉。
public class Solution {
public int reverseBits(int n) {
if (n == 0) return 0;
int res = 0;
for (int i = 0; i < 32; i++) {
res = res << 1;
if ((n & 1) == 1) res++;
n = n >> 1;
}
return res;
}
}