码迷,mamicode.com
首页 > 其他好文 > 详细

Counting Bits(Difficulty: Medium)

时间:2016-05-09 18:36:29      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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:
For num = 5 you should return [0,1,1,2,1,2].

实现:

 1 class Solution {
 2 public:
 3     vector<int> countBits(int num) {
 4    vector<int> result;
 5     for (int i = 0; i <= num; i++)
 6     {
 7         int count = 0;
 8         int j = i;
 9         while (j)
10         {
11             ++count;
12             j = (j-1) & j;
13         }
14         result.push_back(count);
15     }
16     return result;
17     }
18 };

 

Counting Bits(Difficulty: Medium)

标签:

原文地址:http://www.cnblogs.com/lrh-xl/p/5462833.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!