leetcode 1009. Complement of Base 10 Integer

The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.

For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer n, return its complement.

题意:求十进制转为二进制后反码的十进制值。

思路:

对十进制数对应的二进制数每一位进行取反,然后放入结果对应的位置中。

遍历二进制的每一位:

for(int i=0;(1<<i)<=n;i++){
 
}
  • 1.
  • 2.
  • 3.

取出二进制数中的每一位:

第1位i=0

(n>>i)&1
  • 1.

对二进制数的每一位取反:

由于在java中,int和Boolean不能相互转换,所以要分情况讨论

if((n>>i)&1==1){
   res|=0<<i;  
}else{
   res|=1<<i;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

代码:

class Solution {
    public int bitwiseComplement(int n) {
      if(n==0)return 1;
      int res=0;
      for(int i=0;(1<<i)<=n;i++){
         if((n>>i&1)==1){
             res|=0<<i;
         }else{
             res|=1<<i;
         }
      }
      return res;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.