Leetcode 234. 回文链表
338. 比特位计数 - 力扣(LeetCode) (leetcode-cn.com)
思路 1 逃课法:
1. 使用语言的内置方法 bits.OnesCount
func countBits(n int) (result []int) { for i := 0; i <= n; i++ { result = append(result, bits.OnesCount(uint(i))) } return }
思路 2:
1. 自己实现吧,计算海明距离也会用到类似的方法。
2. 如果二进制位的最后一位是1,则 count+=1,否则count+=0。
3. 将这个数整体后移一位,之道这个数不大于0。
func countBits(n int) (result []int) { for i := 0; i <= n; i++ { result = append(result, OneCount(i)) } return } func OneCount(value int) (count int) { for value > 0 { count += value & 1 value >>= 1 } return }