LeetCode 191. Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

分析:题目大意是编写一个函数,函数接收一个无符号整数,并返回该数字二进制表示下“1”的个数。

注意:java中默认是有符号数,在对数字操作时需要注意!

Java代码:

解法一:有两点需要注意

1. 位运算 & 的优先级 低于 比较运算符 == ,括号不能少,为了代码可读性,多写括号偷笑

Java常用符号优先级:

优先级 运算符 结合性
1 () [] . 从左到右
2 ! +(正)  -(负) ~ ++ -- 从右向左
3 * / % 从左向右
4 +(加) -(减) 从左向右
5 << >> >>> 从左向右
6 < <= > >= instanceof 从左向右
7 ==   != 从左向右
8 &(按位与) 从左向右
9 ^ 从左向右
10 | 从左向右
11 && 从左向右
12 || 从左向右
13 ?: 从右向左
14 = += -= *= /= %= &= |= ^=  ~=  <<= >>=   >>>= 从右向左

2. 由于对无符号数操作,用无符号右移 >>>而不是>>

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int cnt = 0;
        while(n != 0){
            // 记得括号,==优先级高于&
            if((n & 1) == 1) cnt++;// 也可写作 cnt += n & 1;
            n = n >>> 1;// 右移时要采用无符号右移,用 >> 会报错。 
        }
        
        return cnt;
    }
}
解法2:

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值