本文共 786 字,大约阅读时间需要 2 分钟。
这道题的输入是一个无符号的整数
有两种办法
把整数变成字符串,遍历字符串查找1的个数,注意,这里不能用String.valueOf
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { String str = Integer.toBinaryString(n); int count = 0; for(int i = 0; i < str.length();i++){ char a = str.charAt(i); if(a == '1') count++; } return count; }}
用31个0和1个1和每一位做与操作,如果该位是1则结果为1,否则为0
与操作的规则是两个都是1则为1,否则为0
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int res = 0; int mask = 1; for(int i = 0; i < 32; i++){ if ((n & mask) != 0) { res++; } mask<<=1; } return res; }
转载地址:http://eejvi.baihongyu.com/