Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.函數
Note:spa
Example 1:code
Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:blog
Input: 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
public int findComplement(int num) { int ans = 0;//the count of the num's bits int temp = num;//copy of the num while(temp != 0){ ans++; temp /= 2; } return num ^ (int)(Math.pow(2,ans)-1); }
pow() 函數用來求 x 的 y 次冪(次方),其原型爲:
double pow(double x, double y);ip