[关闭]
@XQF 2018-03-07T22:55:28.000000Z 字数 265 阅读 881

如何求二进制数中1的个数?

数据结构与算法


  1. public class Solution {
  2. public int countOne(int num) {
  3. int a = 1;
  4. int counter = 0;
  5. for (int i = 0; i < 31; i++) {
  6. if ((a & num) != 0) {
  7. counter++;
  8. }
  9. a <<= 1;
  10. }
  11. return counter;
  12. }
  13. public static void main(String[] args) {
  14. Solution solution = new Solution();
  15. System.out.println(solution.countOne(15));
  16. }
  17. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注