Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
- The given integer is guaranteed to fit within the range of a 32-bit signed integer.
- You could assume no leading zero bit in the integer’s binary representation.
Example 1:
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:
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.
最快算法:
class Solution { public: int findComplement(int num) { int n = num; int mask = 0; while (n) { n >>= 1; mask = (mask << 1) | 1; } return ~num & mask; } };
我的算法:class Solution { public: int findComplement(int num) { int num1 = num; int a[32] = { 0 }; int b[32] = { 0 }; int result = 0; int i = 0; while(num1) { a[i] = num1 % 2; i++; num1 /= 2; } num1 = num; for(i = 0; i < 32 && num1 != 0; i++) { b[i] = 1 - a[i]; num1 -= a[i] * pow(2, i); result += b[i] * pow(2, i); } return result; } };