leetcode 191. Number of 1 Bits

257 篇文章 17 订阅

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.

什么叫unsigned integer呢?默认情况下,java和c++的int都是32位的 第一位是符号位,范围是大概正负2的31次方。 如果是unsigned的话,没有符号位,范围是 0 ~ 2^32-1。
在Java中,不存在Unsigned无符号数据类型,但可以完成Unsigned转换。

//将int数据转换为0~4294967295 (0xFFFFFFFF即DWORD)。
public long getUnsignedIntt (int data){
    return data&0x0FFFFFFFF ;
}
就是说,unsigned int可以在java里用int表示。 因为java把第一位当做符号了。 需要转成long来才能表示。最后可以转int,然后取第一位的bit值,或进去,然后再存。

这道题比较简单。

//you need to treat n as an unsigned value
public int hammingWeight(int n) {
	int count=0;
    for(int i=0;i<32;i++){
    	if((n>>i & 1)==1){
    		count++;
    	}
    }
    return count;
}
我这个方法能够AC。我发现很多大神都更喜欢用<<左移,因为左移肯定补0,不存在 右移中 带符号右移和无符号右移 的歧义。
大神表示:

public static int hammingWeight(int n) {
	int ones = 0;
    	while(n!=0) {
    		ones = ones + (n & 1);
    		n = n>>>1;
    	}
    	return ones;
}

n = n>>>1;

注意到bit shifting是使用的无符号右移 >>> (有符号右移 >>依赖符号扩展)

在java中我们需要注意:最大整数是 2147483647。java中的符号都是 signed,没有 unsigned int 。所以如果输入的 n 是 2147483648 ,在java中将会认为是 -2147483648  (在java中 int 类型 是循环的表达,这意味着 Integer.MAX_VALUE+1==Integer.MIN_VALUE).
这就使得在while循环的判定条件中使用

n!=0

而不能使用:

n>0

因为如果输入的 n 是 2147483648 将会被java认为是 -2147483648 ,导致while根本进不去。

这道题有solutions:https://leetcode.com/problems/number-of-1-bits/solution/

Solution


Approach #1 (Loop and Flip) [Accepted]

Java

public int hammingWeight(int n) {
    int bits = 0;
    int mask = 1;
    for (int i = 0; i < 32; i++) {
        if ((n & mask) != 0) {
            bits++;
        }
        mask = mask<< 1;
    }
    return bits;
}

Complexity Analysis

The time complexity is O(1)O(1).

The space complexity is O(1)O(1), since no additional space is allocated.


Approach #2 (Bit Manipulation Trick) [Accepted]

Algorithm

代替 检查number中的每个 bit 位, 我们重复地把number中的 最低有效1-bit位 翻转为 0, 并且将结果 count 加1。直到number等于0,我们直到再也没有其他的 11-bits 了。

主要思想就是:我们需要知道,对于任意的数 n,将 nn 和 n - 1n1 进行 AND 运算,将会把 最低有效1-bit位 翻转为 0 ,并且让其他 bit位 保持不变。为什么呢? 

Number of 1 Bits

Figure 1. AND-ing nn and n-1n1 flips the least-significant 11-bit to 0.

Java

public int hammingWeight(int n) {
    int sum = 0;
    while (n != 0) {
        sum++;
        n &= (n - 1);
    }
    return sum;
}

Complexity Analysis

The run time depends on the number of 11-bits in nn. In the worst case, all bits in nn are 11-bits. In case of a 32-bit integer, the run time is O(1)O(1).

The space complexity is O(1)O(1), since no additional space is allocated.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值