题目:
请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。
示例 1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’。
示例 2:
输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 ‘1’。
示例 3:
输入:11111111111111111111111111111101
输出:31
解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 ‘1’。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
用二进制的位移算法
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int x = 1;
int counts = 0;
for (int i = 0; i < 32; i++) { //int类型是32位的
if ((x&n) != 0) {
counts++;
}
x = x << 1; //无符号左移
}
return counts;
}
public static void main(String[] args) {
Solution sol = new Solution();
int result = sol.hammingWeight(9);
System.out.println(result);
}
}
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int x = 1;
int counts = 0;
while (n != 0) {
counts += n&1;
n = n >>> 1; //将二进制数无符号右移一位
}
return counts;
}
public static void main(String[] args) {
Solution sol = new Solution();
int result = sol.hammingWeight(9);
System.out.println(result);
}
}
时间复杂度:O(log n),逐位判断需循环 log2^n次
空间复杂度:O(1),只用到counts的常数空间
优化:利用n & (n - 1)
因为每次的n - 1都是二进制的减1(0001)操作,n的最右边的1变成0,1的右边都变成1,n & (n - 1) 中 n的右边都变成0
比如:
*n = 9
*bin 1001
*n - 1 = 1000
*n & (n - 1) = 1000
*||
*n = 8
*bin = 1000
*n - 1 = 0111
*n & (n - 1) =0000
*
*所以counts = 2
public class Solution {
// you need to treat n as an unsigned value
/**
* 优化
* @param n
* @return
*/
public int hammingWeight(int n) {
int x = 1;
int counts = 0;
while (n != 0) {
n = n&(n - 1);
counts++;
}
return counts;
}
public static void main(String[] args) {
Solution sol = new Solution();
int result = sol.hammingWeight(9);
System.out.println(result);
}
}
时间复杂度:O(n),设n为1的个数,只要位移n次
空间复杂度:O(1),只用到counts的常数空间