题目:
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为 汉明重量).)。
提示:
请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
在 Java 中,编译器使用 二进制补码 记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。
来源:力扣(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 static int hammingWeight(int n) {
String str = change(n);
int count=0;
for(int i=0;i<str.length();i++){
if (str.charAt(i) == '1'){
count++;
}
}
return count;
}
public static String change(int n){
String str = Integer.toBinaryString(n);
return str;
}
}
执行结果①:
解题过程②:
public class Solution {
// you need to treat n as an unsigned value
public static int hammingWeight(int n) {
// 循环检查二进制位
int count=0;
for(int i=0;i<32;i++){
// 按位与
if((n & (1<<i)) != 0){
count++;
}
}
return count;
}
}
执行结果②:
复杂度分析
时间复杂度:O(k),其中 k 是 int 型的二进制位数,k=32。我们需要检查 n 的二进制位的每一位,一共需要检查 32 位。
空间复杂度:O(1),我们只需要常数的空间保存若干变量。