题目描述
编写一个函数,确定需要改变几个位,才能将整数A转变成整数B。
给定两个整数int A,int B。请返回需要改变的数位个数。
测试样例:
10,5
返回:4
第一种方法:考察异或
class Transform {
public:
int calcCost(int A, int B)
{
// write code here
int x = A ^ B;
int cnt = 0;
while(x)
{
cnt++;
x = x & (x - 1);
}
return cnt;
}
};
第二种方法:
class Transform {
public:
int calcCost(int A, int B)
{
// write code here
int x = 1;
int cnt = 0;
while(x)
{
if((x & A) != (x & B))
{
cnt++;
}
x <<= 1;
}
return cnt;
}
};