Home > Software engineering >  Why my function is returning 11 instead of 5?
Why my function is returning 11 instead of 5?

Time:01-05

I am trying to solve a problem with leetcode label Compliment of Base 10 Integer. By theory, if you Exclusive OR(XOR) One(1) with any number you will get the compliment of that number. For example, if you XOR ONE(1) With 5(101) you will get 2(010)

Note: Assuming that the input is 10. It is returning 11 instead of 5

This is the link to the question that I am trying to solve

This is what I wrote

class Solution {
public int bitwiseComplement(int n) {
    return (n^1);
}

}

CodePudding user response:

Why 10 ^ 1 = 11 (and not 5)

10 in binary is 1010 and 1 in binary is 0001

now lets calculate 1010 ^ 0001

  1010
^ 0001
  ----
  1011
  ----

1011 in decimal is 11! (since 5 in binary is 0101)

CodePudding user response:

Look at this trick. ~ operation switch 0 <-> 1.

int a = 0b010;
int b = ~a & 0b111; // 0x101

So the solution is pretty simple:

  1. Find the highest 1 bit; it gives you the number of bits for the mask
  2. User ~ to find a compliment number and limit it to the number of bits.
  •  Tags:  
  • Related