一、问题描述
编写一个函数,确定需要改变几个位,才能将整数A转变成整数B。给定两个整数int A,int B。请返回需要改变的数位个数。
测试样例:
10,5
返回:4
二、思路描述
首先对A和B取异或运算,然后计算该数字中的1的个数,本人采用的思路是先判断这个数字是不是负数,然后诸位的判断是不是1。有种更简单的方法是
使用n=n&(n-1)的方法,效率更高
三、代码
import java.util.*;
public class Transform {
public int calcCost(int A, int B) {
// write code here
int a=A^B;
int temp=1;
int numcount=0;
boolean flag=false;//如果a是负数;
if(a<0){
a=-a;
flag=true;
}
while(temp<=a && temp>0){//如果通过将a不断左移来判断a中1的个数,不需要管a是正数还是负数
if((temp&a)!=0){
numcount++;
}
temp=temp<<1;
}
if(flag)
numcount++;
return numcount;
}
}
第二种方式:
import java.util.*;
public class Transform {
public int calcCost(int A, int B) {
// write code here
int a=A^B;
int count=0;
while(a!=0){
a&=(a-1);
count++;
}
return count;
/*
int a=A^B;
int temp=1;
int numcount=0;
boolean flag=false;//如果a是负数
if(a<0){
a=-a;
flag=true;
}
while(temp<=a && temp>0){
if((temp&a)!=0){
numcount++;
}
temp=temp<<1;
}
if(flag)
numcount++;
return numcount;
*/
}
}