Skip to content

Commit e10d3a5

Browse files
committed
Solve problem '190) reverse bits'
1 parent 667dfde commit e10d3a5

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
Reverse bits of a given 32 bits unsigned integer.
2+
3+
**Note:**
4+
5+
- 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.
6+
- In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 2** above, the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`.
7+
8+
**Example 1:**
9+
10+
```
11+
Input: n = 00000010100101000001111010011100
12+
Output: 964176192 (00111001011110000010100101000000)
13+
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
14+
```
15+
16+
**Example 2:**
17+
18+
```
19+
Input: n = 11111111111111111111111111111101
20+
Output: 3221225471 (10111111111111111111111111111111)
21+
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
22+
```
23+
24+
**Constraints:**
25+
26+
- The input must be a **binary string** of length `32`
27+
28+
**Follow up:** If this function is called many times, how would you optimize it?

problems/190-reverse-bits/main.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func main() {
6+
fmt.Println(reverseBits(43261596))
7+
fmt.Println(reverseBits(4294967293))
8+
}
9+
10+
func reverseBits(num uint32) uint32 {
11+
var result uint32
12+
for i := 0; i < 32; i++ {
13+
result = result<<1 | num&1
14+
num >>= 1
15+
}
16+
return result
17+
}

0 commit comments

Comments
 (0)