Leetcode代码学习周记——Number Complement

本文介绍了一种计算整数反码的有效方法。通过不断累加二进制位上的1直至超过目标数值,再将该累加值与原始数值相减,从而得到目标数值的反码。这种方法适用于任何正整数。

题目链接:

https://leetcode.com/problems/number-complement/description/

题目描述:

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

给定一个正整数,计算其反码。

题解:

如给定正整数5 = 101,其反码等于7 - 5 = 111-101 = 010 = 2;所以只需依次增加二进制数每一位1直到大于给定的num,然后相减即可得到答案。

代码:

#include<cmath>
class Solution {
public:
    int findComplement(int num) {
        int i = 0;
        int j = 0;
        while (i < num) {
            i += pow(2, j);
            j++;
        }
        return i - num;
    }
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值