leetcode 1012. Complement of Base 10 Integer
题意:给你一个数,比如5,他的二进制是101,把三个数的每一个取反,得到010,返回2.
思路:简单模拟就好了。0的时候,记得返回1.
class Solution {
public:int bitwiseComplement(int N) {if(N==0) return 1;vector<int> num;while (N){if (N % 2 == 1)num.push_back(0);elsenum.push_back(1);N /= 2;}int ans = 0;int now = 1;for (int i = 0; i < num.size(); i++){ans += num[i] * now;now *= 2;}return ans;}
};