[LeetCode] 190. Reverse Bits

Reverse bits of a given 32 bits unsigned integer.

Note:

  • Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
  • In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.

Example 1:

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

Example 2:

Input: n = 11111111111111111111111111111101
Output:   3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.

Constraints:

  • The input must be a binary string of length 32

Follow up: If this function is called many times, how would you optimize it?

颠倒二进制位。

颠倒给定的 32 位无符号整数的二进制位。

提示:

请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在 示例 2 中,输入表示有符号整数 -3,输出表示有符号整数 -1073741825。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reverse-bits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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

思路是把input从右向左一位位的取出来或者说by digit一步步右移,如果取出来的是1,将结果 res 左移一位并且加上1;如果取出来的是0,将结果 res 左移一位即可。

举个例子,如果要操作的部分是110的话

第一轮

首先res(0)往左移一位还是0,然后判断110的最低位 & 1 = 0,那么res还是0,此时n再右移一位,变成11。

第二轮

此时input是11,res再往左移一位得到00,此时1的最低位 & 1 = 1,那么res就变成01。

第三轮

此时input是1,res再往左移一位得到0010,此时最低位1 & 1 = 1,那么res就变成011

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

空间O(1)

Java实现

 1 public class Solution {
 2     // you need treat n as an unsigned value
 3     public int reverseBits(int n) {
 4         // corner case
 5         if (n == 0) {
 6             return 0;
 7         }
 8 
 9         // normal case
10         int res = 0;
11         for (int i = 0; i < 32; i++) {
12             res <<= 1;
13             if ((n & 1) == 1) {
14                 res++;
15             }
16             n >>= 1;
17         }
18         return res;
19     }
20 }

 

JavaScript实现

 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 };

 

LeetCode 题目总结

posted @ 2020-01-06 07:02  CNoodle  阅读(209)  评论(0)    收藏  举报