c++ - C++负数中对1位的计数

标签 c++ bit-manipulation bitcount

以下功能:

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;
}

关于c++ - C++负数中对1位的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33826507/

相关文章:

c++ - 如何正确理解回车符(又名\r)?

Java - bitCount() 的大 O?

python - 无法编译需要 C99 编译器 (AFAIU) 的 pyethash python 包。错误 - 无法打开包含文件 : 'alloca.h'

c++ - std::ostringstream 缓冲区的最大大小是多少?

bit-manipulation - 如何取消设置最右边的 N 个设置位

python - Python和C.Bitoperation,.split()函数

chess - 一个字节的尾随/前导零计数

c++ - unsigned long long VS unsigned long long int

python - 如何在 Python 中优化 str.replace()