颠倒二进制位
颠倒给定的 32 位无符号整数的二进制位。
示例:
输入: 43261596
输出: 964176192
解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 ,
返回 964176192,其二进制表示形式为 00111001011110000010100101000000 。
思路:
(1)题意为给定无符号32位整数,求该整数翻转(对应的二进制数的翻转)后所得的整数值。
(2)该题主要考察位运算。由于限制位数为32位,所以只需对待处理的整数n进行32次右移位,每当低位&1的结果为1,说明低位为1,此时将待输出的目标整数(默认值为0)左移动一位并加上1;每当低位&1的结果为0,说明低位为0,此时将待输出的目标整数左移一位即可;循环直到移动完32次,所得目标整数即为所求。
(3)详情见下方代码。希望本文对你有所帮助。
1 public class Solution { 2 // you need treat n as an unsigned value 3 public int reverseBits(int n){ 4 int value=0; 5 for(int i=0;i<32;i++){ 6 if((n&1)==1){ 7 value=(value<<1)+1; 8 n>>=1; 9 }else{ 10 value=value<<1; 11 n>>=1; 12 } 13 } 14 return value; 15 } 16 }