[LeetCode] 190. Reverse Bits

颠倒二进制位。题意是给一个数字,请你将其二进制的表达反转过来。例子,

Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

思路是把input从右向左一位位的取出来,如果取出来的是1,将结果 res 左移一位并且加上1;如果取出来的是0,将结果 res 左移一位,然后将n右移一位即可。

时间O(1) - 因为无论如何也就只有32次操作

空间O(1)

 1 /**
 2  * @param {number} n - a positive integer
 3  * @return {number} - a positive integer
 4  */
 5 var reverseBits = function(n) {
 6     if (n === 0) return 0;
 7     var res = 0;
 8     for (var i = 0; i < 32; i++) {
 9         res = res << 1;
10         if ((n & 1) === 1) res++;
11         n = n >> 1;
12     }
13     return res >>> 0;
14 };

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12154601.html