本文共 1251 字,大约阅读时间需要 4 分钟。
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 };
本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/4999835.html,如需转载请自行联系原作者