LeetCode#190: Reverse Bits

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38283262/article/details/84226747

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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38283262/article/details/84226747