leecode_338 Counting Bits

来源:互联网 发布:淘宝buy 宣传片 编辑:程序博客网 时间:2024/06/16 12:17

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.

Example:

Fornum = 5 you should return [0,1,1,2,1,2].

i如果是偶数,则1的位数和i/2相等,如果是奇数,醉靠近他的一个偶数末尾为0,所以+1就行

c++实现:

class Solution {  public:      vector<int> countBits(int num) {          vector<int> cb(num+1, 0);          if (num > 0) {              cb[1] = 1;              for (int i = 2; i <= num; i++) {                  cb[i] = cb[i/2] + cb[i%2];              }          }          return cb;      }  };  


0 0
原创粉丝点击