JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

Reverse bits of a given 32 bits unsigned integer.

Example:

Input: 43261596
Output: 964176192
Explanation: 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?

Code

class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        if(n == 0) return 0;

        int res = 0;
        // 不能使用while(n == 0)
        // 因为当n == 0的时候,仍然需要把res往左移动,直到32位为止
        for(int i = 0; i < 32; i++){
          // 结果往左移动一位,准备进行检查n的当前位是否为1
          res <<= 1;
          // 检查最后一位是不是1,如果是1就把res的当前为赋值为1
          if((n & 1) == 1) res += 1;
          // 准备检查下一位
          n >>= 1;
        }
        return res;
    }
}