[英]Counting number of 1 bits in C++ negative number
以下功能:
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;
}
无符号整数允许在一个简单的循环中计算位。
如果我们谈论这些值,则从有符号转换为无符号会产生无效结果:
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 只是一个黑客。
// 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;
}
count 表示整数 n 中设置的位数,如果整数的大小为 32 位,则
int count =0;
int n = -25 //(given)
for(int k=0;k<32;k++){
if ((n >> k) & 1){
count++;
}
}
return count;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.