Determine the number of bits that are different for two given integers.

Examples

  • 5(“0101”) and 8(“1000”) has 3 different bits

Solution: 不断>>> 32次,看& 1后是否相等。或者先a = a ^ b,不同的bit会是1,相同为0

  public int diffBits(int a, int b) {
    int ans = 0;
    for (int i = 0; i < 32; i++) {
      if((a & 1) != (b & 1)) {
        ans++;
      }
      a = (a >>> 1);
      b = (b >>> 1);
    }
    return ans;
  }

results matching ""

    No results matching ""