面试题 05.06. 整数转换

整数转换。编写一个函数,确定需要改变几个位才能将整数A转成整数B。

示例1:

输入:A = 29 (或者0b11101), B = 15(或者0b01111)
输出:2
示例2:

输入:A = 1,B = 2
输出:2
提示:

A,B范围在[-2147483648, 2147483647]之间

python的负数和普通的不同,& 0xffffffff是转换成32位补码

class Solution:
    def convertInteger(self, A: int, B: int) -> int:
        return bin((A^B)&0xffffffff).count('1')

Java:

class Solution {
    public int convertInteger(int A, int B) {
        return Integer.bitCount(A^B);
    }
}
class Solution {
    public int convertInteger(int A, int B) {
        int x = A ^ B, cnt = 0;
        while (x != 0) {
            x &= (x - 1);
            cnt++;
        }
        return cnt;
    }
}
原文地址:https://www.cnblogs.com/xxxsans/p/13768054.html