力扣练习之位1的个数

我爱海鲸 2022-10-10 21:44:40 初级算法

简介初级算法、其他

原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn1m0i/

解法一:

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;
    }
}

思路:按位遍历n,每一次遍历和1进行按位与运算,统计1出现的次数,>>>表示无符号右移,也叫逻辑右移,即若该数为正,则高位补0,而若该数为负数,则右移后高位同样补0

你好:我的2025