###### tags: `Leetcode` `easy` `bit` `python` `c++` # 190. Reverse Bits ## [題目來源:] https://leetcode.com/problems/reverse-bits/ ## 題目: Reverse bits of a given 32 bits unsigned integer. Note: * Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825. ![](https://i.imgur.com/t6QHK3r.png) #### [圖片來源:] https://leetcode.com/problems/reverse-bits/ ## 解題想法: 兄弟題目: [P191. Number of 1 Bits](/R4rPTOWjTWSS0ZfMkz6A9g) ' >> ' 和 ' << ' 都是位運算,對二進制數進行移位操作 ex: <<2 二進位補兩個0 即乘4 ex: 5 = 101 ' <<2 ' == 10100 == 20 逐一取出最後一位數添加到最左邊高位元即可 ## Python: ``` python= class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): res=0 power=31 while n: #get最右邊的值 用(&1) last=n&1 res+=last<<power n>>=1 power-=1 return res ''' b = bin(n)[:1:-1] return int(b+'0'*(32-len(b)),2) ''' if __name__ == '__main__': result = Solution() n = int('00000010100101000001111010011100', 2) ans = result.reverseBits(n) print(n,ans) ``` ## C++: uint32_t為0~2^32-1 (0x00000000~0xFFFFFFFF) ``` cpp= #include<iostream> using namespace std; class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t res=0; int power=31; while (n>0){ res+= (n&1)<<power; n>>=1; power-=1; } return res; } }; int main(){ Solution res; uint32_t n= 43261596; //binary: 00000010100101000001111010011100 cout<<res.reverseBits(n)<<endl; return 0; } ```