public class Solution { public int[] CountBits(int num) { var ary = new int[num + 1]; for (int i = 0; i <= num; i++) { var count = 0; var cur = i; do { var c = cur % 2; if (c == 1) { count++; } cur = cur / 2; } while (cur != 0); ary[i] = count; } return ary; } }
https://leetcode.com/problems/counting-bits/#/description
另一个版本,246ms:
public class Solution { public int[] CountBits(int num) { int[] counts = new int[num + 1]; for (int i = 0; i <= num; i++) { int n = i; int count = 0; while (n != 0) { if ((n & 1) == 1) { count++; } n >>= 1; } counts[i] = count; } return counts; } }
补充一个使用动态规划思想的代码,使用python实现:
1 class Solution: 2 def countBits(self, num: 'int') -> 'List[int]': 3 if num==0: 4 return [0] 5 elif num==1: 6 return [0,1] 7 else: 8 d = [0] * (num+1) 9 d[0] = 0 10 d[1] = 1 11 for i in range(2,num+1): 12 if i % 2 ==0: 13 d[i] = d[i//2] 14 else: 15 d[i] = d[i//2] + 1 16 return d