标签:
C++
1 class Solution { 2 public: 3 /** 4 * @param num: an integer 5 * @return: an integer, the number of ones in num 6 */ 7 int countOnes(int num) { 8 // write your code here 9 int sum = 0; 10 while (num) { 11 sum ++; 12 num = num&(num-1); 13 } 14 return sum; 15 } 16 };
1 class Solution { 2 public: 3 /** 4 * @param num: an integer 5 * @return: an integer, the number of ones in num 6 */ 7 int countOnes(int num) { 8 // write your code here 9 unsigned int n = num; 10 int sum = 0; 11 while (n) { 12 sum += n&1; 13 n>>=1; 14 } 15 return sum; 16 } 17 };
标签:
原文地址:http://www.cnblogs.com/CheeseZH/p/4999835.html