Easy understand Java solution with comments


  • 1
    W
    // 思路: 设置初始值为0,在对应的位置上做按位或操作
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
    	int result = 0;
    	for (int i = 0; i < 32; i++) {
    		result |= (n >> i & 0x1) << (31 - i); // 取得n特定位的值,设置到result特定位中
    	}
    	return result;
    }

  • 0
    G

    I got a question.
    Why use "0x1" there, instead of "1".
    Thank you.


  • 0
    C

    they are just the same


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.