Q:
Write a function to determine the number of bits required to convert integer A to integer B.
Input: 31, 14
Output: 2
A: 统计A^B二进制中1的个数就即可。
#include <iostream>
using namespace std;
int count_one(int x){
x = (x & (0x55555555)) + ((x >> 1) & (0x55555555));
x = (x & (0x33333333)) + ((x >> 2) & (0x33333333));
x = (x & (0x0f0f0f0f)) + ((x >> 4) & (0x0f0f0f0f));
x = (x & (0x00ff00ff)) + ((x >> 8) & (0x00ff00ff));
x = (x & (0x0000ffff)) + ((x >> 16) & (0x0000ffff));
return x;
}
int count_one2(int x) {
int cnt = 0;
while (x) {
x &= (x-1);
cnt++;
}
return cnt;
}
int convert_num(int a, int b){
return count_one(a^b);
}
int main(){
int a = 7, b = 14;
cout<<convert_num(a, b)<<endl;
return 0;
}
本文介绍了一种计算将一个整数A转换为另一个整数B所需的位数的方法。通过统计A与B进行异或运算后结果中1的个数来实现。提供了两种不同的计数1的个数的方法,并展示了一个简单的示例。
31万+

被折叠的 条评论
为什么被折叠?



