【剑指offer】面试题 15. 二进制中 1 的个数

面试题 15. 二进制中 1 的个数


题目描述

    题目:输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

代码实现

  • 方法一

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count=0;
            while(n!=0){
                count+=(n&1);
                n=n>>>1;
            }
            return count;
        }
    }
  • 方法二

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count = 0;
            while(n!=0){
                n = n&(n-1);
                count++;
            }
            return count;
        }
    }

猜你喜欢

转载自www.cnblogs.com/hglibin/p/9030049.html