给定两个整数A和B。编写函数,返回将整数A转变成整数B所需要改变的数位个数。
测试样例:
10,5
返回:4
首先A转化B要改变多少位,即A和B有多少位不同,异或相同则为0,不同为1,接下来就是求一个数的二进制中的1的个数,剑指offer原题
class Transform {
public:
int calcCost(int A, int B)
{
int num=A^B;
int count=0;
while(num)
{
count++;
num=num&(num-1);
}
return count++;
}
};
# -*- coding:utf-8 -*-
class Transform:
def calcCost(self, A, B):
A=bin(A).replace("0b","").rjust(32,"0")
B=bin(B).replace("0b","").rjust(32,"0")
return sum(map(lambda c:A[c]!=B[c],range(32)))
return sum(map(lambda c:bin(A).replace("0b","").rjust(32,"0")[c]!=bin(B).replace("0b","").rjust(32,"0")[c],range(32)))
//方法一:就是喜欢这么暴力
public int calcCost(int A, int B) {
int n=A^B,count=0;
while(n!=0){
n=n&n-1;//把最右面一个1给他置零
count++;
}
return count;
}
//方法二:
public int calcCost(int A, int B) {
int n=A^B,count=0,index=1;;
while(index!=0){
count+=(index&n)==0?0:1;
index<<=1;
}
return count;
}
import java.util.*;
//直接用Integer内置的bitCount来计算二进制里1的个数
public class Transform {
public int calcCost(int A, int B) {
int sum=A^B;
return Integer.bitCount(sum);
}
} 参考:http://blog.csdn.net/sinat_22797429/article/details/75451808
/*
* 思路:比较A和B每位上数字是否相同,使用异或方式比较
* 获取每位数字的方法:A-(A >>> 1 << 1),A无符号右移1位再左移一位,原数A减去该数,得到最低位的值
* 循环内进行异或比较后,将A >>> 1,因为最低位已比较完毕,故到较高一位比较
*/
public int calcCost(int A, int B) {
// write code here
int res = 0;
while(A != 0 || B != 0){
int Abit = A - (A >>> 1 << 1);
int Bbit = B - (B >>> 1 << 1) ;
if((Abit ^ Bbit) == 1){
res++;
}
A = A >>> 1;
B = B >>> 1;
}
return res;
}
思路:A 需要变换 多少位 才能得到B,位变换无非就是0-1,1-0的过程所以,A和B之间 有多少的不同的0-1,1-0的变换就有需要多少位的变换,由于异或操作是 相同为0 不同为1 也即1-0,0-1的结果为1,也就是转换成A^B之后 1 的个数求解; int calcCost(int A, int B) { // write code here int res = A ^ B; int count = 0; while(res != 0) { if((res & 1) !=0) { count++; } res >>= 1; } return count; } 或者: int calcCost(int A, int B) { // write code here int res = A ^ B; int count = 0; while(res != 0) { count++; //去掉最后一位的1 例如 1111 & (1111-1) = 1110 将最后一位1 去掉 res &= (res-1); } return count; }