476. Number Complement - leetcode

本文介绍了一种求整数补码的有效算法。通过使用掩码(mask)技巧,该算法能够在不引入额外高位1的情况下翻转输入整数的每一位。文章通过两个示例详细解释了算法的工作原理及实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

476.Number Complement

Given apositive integer, output its complement number. The complement strategy is toflip the bits of its binary representation.

Note:

The giveninteger is guaranteed to fit within the range of a 32-bit signed integer.

You couldassume no leading zero bit in the integer’s binary representation.

 

Example1:

Input: 5

Output: 2

Explanation:The binary representation of 5 is 101 (no leading zero bits), and itscomplement is 010. So you need to output 2.

 

Example2:

Input: 1

Output: 0

Explanation:The binary representation of 1 is 1 (no leading zero bits), and its complementis 0. So you need to output 0.

 

输出一个数各位取反之后的数。一开始没考虑直接就 return ~num;

需要注意,一个int 在计算机内部是32位,如果直接取反,前面的0000会变成1111,所以在取反的时候要考虑这种情况。参考了别人的思路,很巧妙,利用mask掩码,来回取反,就出来结果了。

class Solution {
public:
    int findComplement(int num) {
        unsigned mask = ~0;
        while(mask & num){
            mask <<= 1;
        }
        return ~mask & ~num;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值