/** * @param{number} n - a positive integer * @return{number} - a positive integer */varreverseBits=function (n) {let res =0;for (let i =0; i <32; i++) { res = (res <<1) + (n &1); n = n >>>1; }return res >>>0;};
C++ Code:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
auto ret = 0;
for (auto i = 0; i < 32; ++i) {
ret = (ret << 1) + (n & 1);
n >>= 1;
}
return ret;
}
};
Python Code:
classSolution:# @param n, an integer# @return an integerdefreverseBits(self,n): result =0for i inrange(32): result = (result <<1) | (n &1) n >>=1return result# orclassSolution:defreverseBits(self,n:int) ->int: ans =0for i inrange(31, -1, -1): ans |= ((n >> i) &1) << (31- i)return ans
Java Code:
publicclassSolution {publicintreverseBits(int n) {int rev =0;for (int i =0; i <32&& n !=0; ++i) { rev |= (n &1) << (31- i); n >>>=1; }return rev; }}