leetcode181:将整数A转换为B

1、

  如果要将整数A转换为B,需要改变多少个bit位?

     如把31转换为14,需要改变2个bit位。

    (31)10=(11111)2

    (14)10=(01110)2

2、思路:

  1、用位运算符^,如果不相同时,变为1.

  2、统计该二进制里面存有几个1的个数即可

  

public static int replaceOf(int a, int b ){
        int c = a^b;
        int count = 0;
        String strs = Integer.toBinaryString(c);
        for(char str : strs.toCharArray()){
            if(str == '1'){
                count++;
            }
        }
        return count;
    }

  2.2使用&来判断1的个数。效率更快

  

public static int replaceOf2(int a, int b ){
        int c = a^b;
        int count =0;
        while(c != 0){
            count++;
            c = c&(c-1);
        }
        return count;
    }
工作小总结,有错请指出,谢谢。
原文地址:https://www.cnblogs.com/zilanghuo/p/5238976.html