Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

190. Reverse Bits #59

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

设这个数为k,用一个初值为0的数r保存反转后的结果,用1对k进行求与,其结果与r进行相加,再对k向右进行一位移位,对r向左进行一位移位。值到k的最后一位处理完。 &与运算 &作为位运算时,1&1=1 ,1&0=0,0&0=0 |表示的是或运算,即两个二进制数同位中,只要有一个为1则结果为1,若两个都为1其结果也为1 ^ 异或 0 ^ 1 得 1 1 ^ 1 得 0 0 ^ 0 得 0 1 ^ 0 得 1

public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int res = 0; for(int i = 0; i < 32; i++) { res = res + (n&1); n = n>>>1; //n >>>= 1; if(i < 31) { res = res<<1; // res <<= 1; } } return res; } }

Shawngbk commented 7 years ago

Airbnb Apple