문제설명
- 32비트 unsigned 정수가 주어졌을 때, 비트를 뒤집어서 반환하라
문제풀이
- 입력된 정수의 비트를 하나하나씩 새로운 변수에 옮겨준다.
- 32비트 unsigned 정수는 32자리 비트가 모두 1로 채워진다.
- 32비트 unsigned 정수의 최대값인 2^32 을 뒤집으면, 그대로 2^32이 나온다.
func reverseBits(_ n: Int) -> Int {
var result = 0
var num = n
for i in 0..<32 {
result |= (num & 1) << (31 - i)
num = num >> 1
}
return result
}
print(String(reverseBits(1), radix: 2)) // 10000000000000000000000000000000
print(String(reverseBits(2), radix: 2)) // 1000000000000000000000000000000
print(String(reverseBits(Int(Int32.max)), radix: 2)) // 11111111111111111111111111111110
'알고리즘풀이' 카테고리의 다른 글
LeetCode: Valid Parentheses (0) | 2021.03.25 |
---|---|
LeetCode: Pascal's Triangle, 파스칼 삼각형 (0) | 2021.03.24 |
LeetCode: Hamming Distance, 해밍 거리 (0) | 2021.03.21 |
LeetCode: Number of 1 Bits (0) | 2021.03.20 |
Leetcode: Roman to Integer (0) | 2021.03.18 |