LeetCode 颠倒二进制位

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

颠倒给定的 32 位无符号整数的二进制位。

示例:

输入: 43261596
输出: 964176192
解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 ,
返回 964176192,其二进制表示形式为 00111001011110000010100101000000

思路
二进制一般和位运算有关,可以直接通过Integer转换二进制然后遍历叠加
但是有更好的办法,代码如下,带有注释

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int result = 0;
        int i = 0;
        while(i<32){
            int temp = n&1;  //得到最后一位  0或者1
            n = n>>1;    //左移动1位
            result = result<<1|temp;  //首先把二进制往右边移动1位,然后|操作,1010右移  10100|1==10101
            i++;
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_33330687/article/details/81903145