Skip to content

Commit dc49329

Browse files
committed
bit.190
1 parent 4bb4df0 commit dc49329

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* @lc app=leetcode.cn id=190 lang=golang
3+
*
4+
* [190] 颠倒二进制位
5+
*
6+
* https://leetcode.cn/problems/reverse-bits/description/
7+
*
8+
* algorithms
9+
* Easy (71.68%)
10+
* Likes: 596
11+
* Dislikes: 0
12+
* Total Accepted: 200.3K
13+
* Total Submissions: 279.5K
14+
* Testcase Example: '00000010100101000001111010011100'
15+
*
16+
* 颠倒给定的 32 位无符号整数的二进制位。
17+
*
18+
* 提示:
19+
*
20+
*
21+
* 请注意,在某些语言(如
22+
* Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
23+
* 在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在 示例 2 中,输入表示有符号整数 -3,输出表示有符号整数
24+
* -1073741825。
25+
*
26+
*
27+
*
28+
*
29+
* 示例 1:
30+
*
31+
*
32+
* 输入:n = 00000010100101000001111010011100
33+
* 输出:964176192 (00111001011110000010100101000000)
34+
* 解释:输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
35+
* ⁠ 因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000。
36+
*
37+
* 示例 2:
38+
*
39+
*
40+
* 输入:n = 11111111111111111111111111111101
41+
* 输出:3221225471 (10111111111111111111111111111111)
42+
* 解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293,
43+
* ⁠   因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。
44+
*
45+
*
46+
*
47+
* 提示:
48+
*
49+
*
50+
* 输入是一个长度为 32 的二进制字符串
51+
*
52+
*
53+
*
54+
*
55+
* 进阶: 如果多次调用这个函数,你将如何优化你的算法?
56+
*
57+
*/
58+
package jzoffer
59+
60+
import (
61+
"fmt"
62+
"strconv"
63+
)
64+
65+
// @lc code=start
66+
func reverseBitsUsingString(n uint32) (rev uint32) {
67+
// 00000010100101000001111010011100
68+
b := []byte(fmt.Sprintf("%032b", n)) // 必须使用032 保证输出足够的32为,不够补0
69+
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
70+
b[i], b[j] = b[j], b[i]
71+
}
72+
// fmt.Println(string(b))
73+
res, _ := strconv.ParseInt(string(b), 2, 64) // 32可能长度不够最高位会丢失,故用64
74+
return uint32(res)
75+
}
76+
77+
func reverseBits(n uint32) (rev uint32) {
78+
for i := 0; i < 32 && n > 0; i++ {
79+
rev |= n & 1 << (31 - i) // 从高位到低位把位置上的1依次取出
80+
n >>= 1
81+
}
82+
return
83+
}
84+
85+
// @lc code=end

0 commit comments

Comments
 (0)