面试题 05.06. 整数转换-----位运算

题目表述

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

示例:

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

位运算

依次判断A和B各位置上面的数字是否相同,如果不相同则改变位数res+1

class Solution {
    public int convertInteger(int A, int B) {
        int res = 0;
        for(int i = 0;i < 32; i++){
            if(((1<<i) & A) != ((1<<i) & B)){
                res++;
            }
        }
        return res;
    }
}

位运算2

先将A,B进行异或操作,异或是对A,B二进制位进行操作的,对A和B二进制每一位进行比较,相同结果为0,不同结果为1。所以我们只需要将A,B异或的结果二进制位中1的个数统计出来即不同的个数。

int convertInteger(int A, int B){
int tmp =A^B;
int count = 0;
for(int i =0; i < 32; i++)
{
    if((tmp>>i)&1 ==1)
    {
        count++;
    }
}
return count;
}

posted @ 2022-05-19 23:17  YoungerWb  阅读(44)  评论(0)    收藏  举报