-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathReverseBits.java
More file actions
63 lines (58 loc) · 2.54 KB
/
Copy pathReverseBits.java
File metadata and controls
63 lines (58 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* <p>颠倒给定的 32 位无符号整数的二进制位。</p>
*
* <p><strong>提示:</strong></p>
*
* <ul>
* <li>请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。</li>
* <li>在 Java 中,编译器使用<a href="https://baike.baidu.com/item/二进制补码/5295284" target="_blank">二进制补码</a>记法来表示有符号整数。因此,在 <strong>示例 2</strong> 中,输入表示有符号整数 <code>-3</code>,输出表示有符号整数 <code>-1073741825</code>。</li>
* </ul>
*
* <p> </p>
*
* <p><strong>示例 1:</strong></p>
*
* <pre>
* <strong>输入:</strong>n = 00000010100101000001111010011100
* <strong>输出:</strong>964176192 (00111001011110000010100101000000)
* <strong>解释:</strong>输入的二进制串 <strong>00000010100101000001111010011100 </strong>表示无符号整数<strong> 43261596</strong><strong>,
* </strong> 因此返回 964176192,其二进制表示形式为 <strong>00111001011110000010100101000000</strong>。</pre>
*
* <p><strong>示例 2:</strong></p>
*
* <pre>
* <strong>输入:</strong>n = 11111111111111111111111111111101
* <strong>输出:</strong>3221225471 (10111111111111111111111111111111)
* <strong>解释:</strong>输入的二进制串 <strong>11111111111111111111111111111101</strong> 表示无符号整数 4294967293,
* 因此返回 3221225471 其二进制表示形式为 <strong>10111111111111111111111111111111 。</strong></pre>
*
* <p> </p>
*
* <p><strong>提示:</strong></p>
*
* <ul>
* <li>输入是一个长度为 <code>32</code> 的二进制字符串</li>
* </ul>
*
* <p> </p>
*
* <p><strong>进阶</strong>: 如果多次调用这个函数,你将如何优化你的算法?</p>
* <div><div>Related Topics</div><div><li>位运算</li><li>分治</li></div></div><br><div><li>👍 485</li><li>👎 0</li></div>
*/
package leetcode8;
public class ReverseBits {
public static void main(String[] args) {
Solution solution = new ReverseBits().new Solution();
}
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res = 0;
for (int i = 31; i >= 0; i--) {
res += (n & 1) << i;
n >>>= 1;
}
return res;
}
}
}