原题
https://leetcode-cn.com/problems/convert-integer-lcci/
题解
思路
两数异或后查看比特数
方法一
分开正负数字
/*
*@v7fgg
*执行用时 :0 ms, 在所有 Java 提交中击败了100.00%的用户
*内存消耗 :36.5 MB, 在所有 Java 提交中击败了100.00%的用户
*2020年6月18日 9:40
*/
class Solution {
public int convertInteger(int A, int B) {
//先考虑非负数
if(A>=0&&B>=0){
int c=A^B;
int ans=0;
while(c!=0){
ans+=c%2==0?0:1;
c/=2;
}
return ans;
}
//复数需要加intmin,同时改变符号位,其他位不变
else if(A<0&&B<0){
return convertInteger(A-(-2147483648),B-(-2147483648));
}
//正负性不同,那么把其中一个只改变符号位,其他位不变,返回的结果要加1
else{
return convertInteger(A-(-2147483648),B)+1;
}
}
}
方法二
直接内置函数计算比特
/*
*@v7fgg
*执行用时 :0 ms, 在所有 Java 提交中击败了100.00%的用户
*内存消耗 :36.7 MB, 在所有 Java 提交中击败了100.00%的用户
*2020年6月18日 9:46
*/
class Solution {
public int convertInteger(int A, int B) {
return Integer.bitCount(A^B);
}
}
方法三
参考资料:https://leetcode-cn.com/problems/convert-integer-lcci/solution/shuang-bai-java-by-zn5201314/