338.counting-bits.go 311 B

12345678910111213141516
  1. func countBits(num int) []int {
  2. res := make([]int, num+1)
  3. if num == 0 {
  4. return res
  5. }
  6. res[1] = 1
  7. for i, j := 2, 0; i <= num; i++ {
  8. if i&1 == 0 { // If i is even, bits(i) = bits(i/2)
  9. j++
  10. res[i] = res[j]
  11. } else { // If i is odd, bits(i) = bits(i/2) + 1
  12. res[i] = res[j] + 1
  13. }
  14. }
  15. return res
  16. }