Leetcode Note: Go - Reverse Bits
Reverse Bits - LeetCode
https://leetcode.com/problems/reverse-bits/
- Go 言語で取り組んだメモ
所感
- 久しぶりにコードの問題がきた
回答
Golang solution (without bit ops :) ) - LeetCode Discuss
https://leetcode.com/problems/reverse-bits/discuss/387487/Golang-solution-(without-bit-ops-%3A)-)
func reverseBits(num uint32) uint32 {
var reverse uint32
for i := 0; i < 32; i++ {
reverse *= 2
if num != 0 {
reverse += num % 2
num /= 2
}
}
return reverse
}
- for で 0 から 32 以下までループ。 32 は問題で課されている最大 length 値
- reverse を x2
- 初期値は 0
- num が 0 以外なら
- reverse に num % 2 を加算
- num を 2 で除算
- reverse を x2
Reverse Bits
https://afteracademy.com/blog/reverse-bits
Bit-reversal permutation - Wikipedia
https://en.wikipedia.org/wiki/Bit-reversal_permutation