当前位置: 代码迷 >> 综合 >> leetcode 1012. Complement of Base 10 Integer
  详细解决方案

leetcode 1012. Complement of Base 10 Integer

热度:24   发布时间:2024-01-16 17:56:35.0

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;}
};

 

  相关解决方案