您的位置:首页 > 其它

careercup5.5求解转换两数所需修改的位数

2013-05-10 15:16 302 查看
Write a function to determine the number of bits required to convert integer A to integer B.

Input: 31, 14

Output: 2

首先利用xor异或运算算出两数不同的位数,假设输入的两数为a,b,X=a^b,X中含有的1的位数即为要求的值

为了求出X中1的位数,可以每次把X与1进行and(&)操作,累加低位的1,然后把低位1累加之后对X进行右移操作。

#include<iostream>
using namespace std;
int diff_bits(int a,int b){
int count=0;
for(int i=a^b;i>0;i>>=1){
//每次累加低位的1,如果低位数字为1的话
count+=i&1;
}
return count;
}
int main(){
cout<<diff_bits(31,14)<<endl;
//for test
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: