Featured image of post reverseBits

reverseBits

190. reverseBits

分析

核心步骤:取二进制数的第i位n >> i & 1

res每次左移一位,然后将n的最低位加到res上

C++代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
public:
    uint32_t reverseBits(uint32_t n)
    {
      uint32_t res = 0;
      for (int i = 0; i < 32; ++ i)
        res = (res << 1) + (n >> i & 1);
      return res;
    }
};
Built with Hugo
Theme Stack designed by Jimmy