颠倒给定的 32 位无符号整数的二进制位。
示例 1:
输入: 00000010100101000001111010011100
输出: 00111001011110000010100101000000
解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-bits
解题思路
从最高位到最低位,逐位取出加到结果
result += (n & (1 << (31 - i))) != 0 ? 1 << i : 0
,i
从0
到31
该语句的意思是如果n
在31 - i
位上不为0
则结果加上1
左移i
位
代码
public class Solution {
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
result += (n & (1 << (31 - i))) != 0 ? 1 << i : 0;
}
return result;
}
}