Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.c++
Example:
For num = 5
you should return [0,1,1,2,1,2]
.數組
Follow up:ui
給定一個整數N,輸出一個有N+1個元素的數組,第i個元素是0··i··N,該數字含1的位的個數spa
按照2n分開,由於n是該數字的總共位數code
0 1blog
0 1leetcode
……it
2 3io
10 11 function
……
4 5 6 7
100 101 110 111
……
可見:2n開始,每一個奇數加一,偶數不變
public class Solution { public int[] CountBits(int num) { int[] returnSize = new int[num + 1]; int count = 0; int k = 1; while (num >= k || (num < k && num >= k>>1) ) { int temp = 0; if (count > 1) { temp = 1; } for (; count < k && count <= num; count++) { if ((count & 1) == 1)//奇數 { returnSize[count] = ++temp; } else { returnSize[count] = temp; } } k = k << 1; } return returnSize; } }
問題:在VS中能夠獲得的正確結果在leetcode中不能獲得