1 package Today; 2 //LeetCode:476. Number Complement 3 /* 4 Given a positive integer, output its complement number. 5 The complement strategy is to flip the bits of its binary representation. 6 7 Note: 8 The given integer is guaranteed to fit within the range of a 32-bit signed integer. 9 You could assume no leading zero bit in the integer’s binary representation.10 Example 1:11 Input: 512 Output: 213 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.14 Example 2:15 Input: 116 Output: 017 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.18 */19 public class findComplement476 {20 public static int findComplement(int num) {21 int bits=0;22 int number=num;23 while(number>0){24 bits++;25 number=number>>1;26 }27 return num^(int)(Math.pow(2,bits)-1);28 }29 //study 原来有方法可以直接得到最高bit位30 public static int findComplement2(int num){31 return num^((Integer.highestOneBit(num)<<1)-1);32 }33 public static void main(String[] args) {34 //TODO Auto-generated method stub35 System.out.println(findComplement(5));36 System.out.println(findComplement(1));37 System.out.println(findComplement2(5));38 System.out.println(findComplement2(1));39 40 }41 42 }