Last active
September 19, 2018 15:36
-
-
Save frankchang0125/c4eb7c756e8c41879188abccd7fee59f to your computer and use it in GitHub Desktop.
338. Counting Bits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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