How to Convert Every Bit of a Binary Integer

LC476 Number Complement

the following is very low, but it worked:

//return the conponent of the given number, which means convert every digital in its binary representation.
class Solution {
    public int findComplement(int num) {
        int res = 0;
        List<Integer> list = new ArrayList<>();
        while (num > 0) {
            int last = num % 2;
            list.add(last);
            num /= 2;
        }
        int len = list.size();
        for (int i = 0; i< len; i++) {
            if (list.get(i) == 0) { //means we have to convert this digit into 1
                res = res + (int)Math.pow(2, i);
            }
            
        }
        return res;
    }
}

but before you think about this problem, think this: what makes 0 to 1 and 1 to 0? well, the answer is XOR, because 0^1 =1 and 1^1=0, and 0^0=0 and 1^0=1so maybe we have construct the binary number with the same length as given number, and all the digits in this constructed number is 1, then we XOR this two numbers.

class Solution {
  public int findComplement(int num) {
    // n is a length of num in binary representation
    **int n = (int)( Math.log(num) / Math.log(2) ) + 1; //this statement is used for calculate the length of binary num length**
    // bitmask has the same length as num and contains only ones 1...1
    **int bitmask = (1 << n) - 1; //this statement is used for construct the all 1 with length of n**
    // flip all bits
    return bitmask ^ num;
  }
}

OR we can solve this problem bit by bit: which means flip one bit at a time.

class Solution {
  public int findComplement(int num) {
    int todo = num, bit = 1;
    while (todo != 0) {
      // flip current bit
      num = num ^ bit; //
      // prepare for the next run
      bit = bit << 1; 
      todo = todo >> 1; //todo variable use for keep track of the steps of this while statement, num is that one who XOR with bit exery time.
    }
    return num;
  }
}
posted @ 2020-05-05 01:24  EvanMeetTheWorld  阅读(20)  评论(0)    收藏  举报