题目: Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note: 1. The given integer is guaranteed to fit within the range of a 32-bit signed integer. 2. 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.
思路: 给定一个整数,二进制形式小于32位,且没有前导0,求它的取反后的数。
代码:
class Solution { public: int findComplement(int num) { vector<int> b_num; int result = 0; while (num>0){//将这个整数转换成二进制形式保存在b_num中 b_num.push_back(num % 2); num /= 2; } for (vector<int>::iterator iter = b_num.begin(); iter != b_num.end(); ++iter){ *iter ^= 1;//每一位与1异或,即取反求 } for (int i = 0; i != b_num.size(); i++){//再将其转换成十进制 result += b_num[i] * pow(2, i); } return result; } };