Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
题目含义:反转一个32位无符号的整数。
思路:设这个数为k,用一个初值为0的数r保存反转后的结果,用1对k进行求与,其结果与r进行相加,再对k向右进行一位移位,对r向左进行一位移位。值到k的最后一位处理完。
1 public int reverseBits(int n) { 2 int res = 0; 3 // for (int i = 0; i < 32; ++i) { 4 // res |= ((n >> i) & 1) << (31 - i); 5 // } 6 // return res; 7 for(int i = 0; i < 32; i++) 8 { 9 res = (res << 1) + (n & 1); 10 n = n >> 1; 11 } 12 return res; 13 }
相关题目:7. Reverse Integer