476 Number Complement

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.

 

这道题给了我们一个数,让我们求补数。通过分析题目汇总的例子,我们知道需要做的就是每个位翻转一下就行了,但是翻转的起始位置上从最高位的1开始的,前面的0是不能被翻转的,所以我们从高往低遍历,如果遇到第一个1了后,我们的flag就赋值为true,然后就可以进行翻转了,翻转的方法就是对应位异或一个1即可,参见代码如下:

 

解法一:

class Solution {

public:

    int findComplement(int num) {

        bool start = false;

        for (int i = 31; i >= 0; --i) {

            if (num & (1 << i)) start = true;

            if (start) num ^= (1 << i);

        }

        return num;

    }

};

由于位操作里面的取反符号~本身就可以翻转位,但是如果直接对num取反的话就是每一位都翻转了,而最高位1之前的0是不能翻转的,所以我们只要用一个mask来标记最高位1前面的所有0的位置,然后对mask取反后,与上对num取反的结果即可,参见代码如下:

class Solution {

public:

    int findComplement(int num) {

        int mask = INT_MAX;

        while (mask & num) mask <<= 1;

        return ~mask & ~num;

    }

};

一种迭代的写法,思路就是每次都右移一位,并根据最低位的值先进行翻转,如果当前值小于等于1了,就不用再调用递归函数了:

class Solution {

public:

 int findComplement(int num) {

return (1 - num % 2) + 2 * (num <= 1 ? 0 : findComplement(num / 2));

 }

 };

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值