程序员面试金典-面试题 05.06. 整数转换

题目:

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

示例1:

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

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

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

分析:

很容易的一道题,统计两个数每一位不同的次数,便是需要改变的位数。

程序:

class Solution {
    public int convertInteger(int A, int B) {
        int res = 0;
        int num = 1;
        for(int i = 0; i < 32; ++i){
            if((A & num) != (B & num))
                res++;
            num <<= 1;
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/silentteller/p/12448507.html