计数C++负数中的1位

Counting number of 1 bits in C++ negative number

本文关键字:1位 C++ 计数      更新时间:2023-10-16

以下函数:

int numOnesInBinary(int number) {
    int numOnes = 0;
    while (number != 0) {
        if ((number & 1) == 1) {
            numOnes++;
        }
        number >>= 1;
    }
    return numOnes;
}

只适用于正数,因为在负数的情况下,执行>>操作时,它总是在最左边的位上加一个1。在Java中,我们可以使用>>,但如何在C++中实现呢?我在一本书中读到,我们可以在C++中使用无符号整数,但我不明白如何使用,因为无符号整数不能表示负数。

number强制转换为unsigned int并对其执行计数:

int numOnesInBinary(int number) {
    int numOnes = 0;
    unsigned int unumber = static_cast<unsigned int>(number);
    while (unumber != 0) {
        if ((unumber & 1) == 1) {
            numOnes++;
        }
        unumber >>= 1;
    }
    return numOnes;
}
// How about this method, as hinted in "C Book" by K & R.
// Of course better methods are found in MIT hackmem   
// http://www.inwap.com/pdp10/hbaker/hakmem/hakmem.html  
//
int numOnesInBinary(int number) {
    int numOnes = 0;
    // Loop around and repeatedly clear the LSB by number &= (number -1).  
    for (; number; numOnes++, number &= (number -1));
    return numOnes;
}

无符号整数允许在简单循环中计数位。

如果我们谈论值,从有符号到无符号的转换将导致无效结果:

char c = -127;
unsigned char u = (unsigned char)c; // 129

但如果我们只谈论形式,它不会改变:

1 0 0 0 0 0 0 1 == decimal signed -127
1 0 0 0 0 0 0 1 == decimal unsigned 129

所以选为unsigned只是一个技巧。

count表示整数n中的集合位数如果整数的大小是32位,则

int count =0;  
int n = -25 //(given)
for(int k=0;k<32;k++){
     if ((n >> k) & 1){
        count++;
     }
}
return  count;