题目链接:
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;
}
};

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

被折叠的 条评论
为什么被折叠?



