【LeetCode】476. Number Complement

题目:求补数

思路:首先,理解一下

5 --> 101

2 --> 010

5 + 2 = 111

那么已知5,要求5的补数就需要知道111,也就是1000-1(此处为二进制表示)

代码如下

#include <iostream>
#include <unordered_map>
#include <vector>
#include <array>
using namespace std;


class Solution {
public:
    int findComplement(int num) {
        //i = num + 1 + com(例如 8 = 5 + 1 + 2)写成2进制好看些
        int temp = num;
        int i = 1;
        while(num){
            num /= 2; 
            i *= 2;
        }
        int res = i - 1 - temp;
		return res;
    }
};
int main(){
	Solution s;
	int num = 9;
	int re = s.findComplement(num);
	cout << re << endl;
	system ("pause");
	return 0;
}

方法2:

这个是参考网上大神写的,一开始有点懵,看不太懂,自己举了个例子,然后写成二进制,一步步地走了一遍后,发现思路很简单

以9为例,9 --> 0000 1001

理想结果    --> 0000 0110

            ~9 --> 1111 0110

那么就需要~9&num num --> 0000 1111  ~num = 1111 0000(那么想办法得到1111 0000 就好啦)

#include <iostream>
#include <unordered_map>
#include <vector>
#include <array>
using namespace std;


class Solution {
public:
    int findComplement(int num) {
		int mask = ~0;
		while(num & mask)
			mask <<= 1;
		return ~num & ~mask;
    }
};
int main(){
	Solution s;
	int num = 9;
	int res = s.findComplement(num);
	cout << res << endl;
	system ("pause");
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值