Base 10 整数的补码
给定一个基数为 10 的整数 N,任务是找到这个基数为 10 的整数的 1 的补码。
例子:
Input: N = 5
Output: 2
Explanation: Binary representation of 5 is “101”. Its one’s complement is “010” = 2.
Input: N = 255
Output: 0
方法:这里的数字是通过翻转位并将2的幂加到答案中来转换的。按照下面提到的步骤来实现它:
- 找到N的二进制表示。
- 对于每一位,翻转它并将该位的贡献添加到最终答案中。
- 返回最终答案
下面是上述方法的实现。
C++
// C++ code to implement above approach
#include
using namespace std;
// Function to find the complement
int findComplement(int num)
{
int ans = 0;
for (int i = 0; num > 0; i++) {
ans += pow(2, i) * (!(num % 2));
num /= 2;
}
return ans;
}
// Driver code
int main()
{
unsigned int N = 5;
cout << findComplement(N);
return 0;
}
Java
// Java code to implement above approach
class GFG {
// Function to find the complement
static int findComplement(int num)
{
int ans = 0, x;
for (int i = 0; num > 0; i++) {
if (num % 2 == 1) {
x = 0;
}
else {
x = 1;
}
ans += (int)Math.pow(2, i) * x;
num /= 2;
}
return ans;
}
// Driver code
public static void main(String[] args)
{
int N = 5;
System.out.print(findComplement((int)N));
}
}
// This code is contributed by ukasp.
Python
# Python code to implement above approach
# Function to find the complement
def findComplement(num):
ans = 0;
x = 0;
i = 0;
while(num > 0):
if (num % 2 == 1):
x = 0;
else:
x = 1;
ans += pow(2, i) * x;
num //= 2;
i += 1;
return ans;
# Driver code
if __name__ == '__main__':
N = 5;
print(findComplement(N));
# This code is contributed by 29AjayKumar
C#
// C# code to implement above approach
using System;
class GFG
{
// Function to find the complement
static int findComplement(int num)
{
int ans = 0, x;
for (int i = 0; num > 0; i++) {
if(num % 2 == 1) {
x = 0;
}
else {
x = 1;
}
ans += (int)Math.Pow(2, i) * x;
num /= 2;
}
return ans;
}
// Driver code
public static void Main()
{
uint N = 5;
Console.Write(findComplement((int)N));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
2
时间复杂度: O(logN)
辅助空间: O(1)