面试题 05.06. 整数转换

题目

整数转换。编写一个函数,确定需要改变几个位才能将整数A转成整数B。
示例1:
输入:A = 29 (或者0b11101), B = 15(或者0b01111)
输出:2

解题思路

根据题意可得,求A与B的不同位的数量?

  • 相同的位异或结果为0,不同位异或结果为1,求A异或B的结果中的1的个数
  • 逐位判断,值是否为1
    • 若为1,不同位的数量+1
    • 否则,数量不变

代码

class Solution {
  public int convertInteger(int A, int B) {
    int xor = A ^ B, ans = 0;
    for (int i = 0; i < 32; i++) {
      ans += (xor & 1) == 1 ? 1 : 0;
      xor >>= 1;
    }
    return ans;
  }
}

题目来源:力扣(LeetCode)

你可能感兴趣的:(算法,LeetCode,位运算,异或,leetcode题解,力扣题解,java)