Leetcode题解之其他(3)颠倒二进制位

题目:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/26/others/66/

题目描述:

颠倒二进制位

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

示例:

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

思路:参考别人的思路。自己想的都是转字符串 转字符数组这些烂方法。

    达到目的:将n的末位给res的首位,再调整它们的首位,末位。 每次赋值都将n右移位,将res左移1位。这里赋值是用一个int temp = n&0x01 通过与运算来一位一位赋值,res获得值也是有点技巧的 每次向左移一位后做或运算 (res<<1)| temp。

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int res = 0 ;
        int i =0;
        while(i<32){
            int temp =n&0x01;
            n= n>>1;
            res = (res<<1)|temp;
            i++;
        }
        return res;
    }
}
方法2:
public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int count =0;
        for(int i = 31;i>=;i--){
            count = (n>>>i&1)<<(31-i)|count;
        }
        return count ;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34433210/article/details/84585151
今日推荐