题目描述
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
示例 1:
Assert::That(countBits(0), Equals(0));
示例 2:
Assert::That(countBits(7), Equals(3));
示例 3:
Assert::That(countBits(9), Equals(2));
提示:
考虑位运算
方法一、循环取余
思路总结
判断最后一位是否为一,是则计数加一。令number%=2
,number/=2
进入下一位判断。
代码
unsigned int countBits(unsigned long long n){
//your code here
int cnt = 0;
while(n>0){
if(n%2 == 1){
++cnt;
}
n/=2;
}
return cnt;
}
方法二、与运算
思路总结
代码
unsigned int countBits(unsigned long long n){
int count = 0;
while (n) {
n &= (n-1);
++count;
}
return count;
}
总结
在底层处理方面,位运算和算术运算之间也有一些区别。
算术运算通常需要使用CPU的算术逻辑单元(ALU) 来执行。ALU是一种硬件电路,可以对数字进行基本的算术运算,例如加法、减法、乘法和除法等。这些操作都是通过二进制补码表示的数字来完成的。
而位运算通常可以通过CPU的逻辑门电路(logic gates)来实现。逻辑门电路是一种基于二进制逻辑的电路,可以实现基本的逻辑操作,例如与、或、非和异或等。这些操作可以用来执行位运算操作,例如按位与、按位或、按位异或和位移等。
因为位运算是在逻辑门电路上执行的,所以它们的处理速度通常比算术运算更快。 此外,位运算也可以更容易地被优化为CPU的硬件电路,从而进一步提高它们的执行速度。
总的来说,在底层处理方面,位运算和算术运算之间的差异主要在于它们所使用的硬件电路和执行速度上的差异。但在编写代码时,我们通常不需要考虑这些底层实现的细节,而只需要根据具体需求选择适当的运算符即可。