Skip to content

Instantly share code, notes, and snippets.

@frankchang0125
Last active September 19, 2018 15:36
Show Gist options
  • Save frankchang0125/c4eb7c756e8c41879188abccd7fee59f to your computer and use it in GitHub Desktop.
Save frankchang0125/c4eb7c756e8c41879188abccd7fee59f to your computer and use it in GitHub Desktop.
338. Counting Bits
func countBits(num int) []int {
results := make([]int, num+1)
bitsMap := []int{0, 1, 1, 2}
base := 4
for i := 0; i < 4; i++ {
if i > num {
return results
}
results[i] = bitsMap[i]
}
bitsMapIndex := 0
for i := 4; i <= num; i++ {
if i == base*2 {
base = base * 2
bitsMapIndex = 0
}
results[i] = 1 + bitsMap[bitsMapIndex]
bitsMap = append(bitsMap, 1+bitsMap[bitsMapIndex])
bitsMapIndex++
}
return results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment