求整数的补码 |设置 2
给定一个整数N ,找到整数的反码。
例子:
Input: N = 5
Output: 2
Explanation: Binary representation of 5 is “101”. Its one’s complement is “010” = 2.
Input: N = 255
Output: 0
Input: N = 26
Output: 5
方法:文章的 Set-1 中已经提到了基于 XOR 的方法和将数字转换为二进制数的方法。在这里,数字是通过翻转位并将 2 的幂添加到答案来转换的。按照下面提到的步骤来实现它:
- 求 N 的二进制表示。
- 对于每个位,对其进行补充并将该位的贡献添加到最终答案中。
- 返回最终答案
下面是上述方法的实现。
C++
// CPP program to find 1's complement of N.
#include
using namespace std;
// Find the 1's complement of N
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 for the above approach
import java.util.*;
public class GFG
{
// Find the 1's complement of N
static int findComplement(int num)
{
int ans = 0;
for (int i = 0; num > 0; i++) {
if(num % 2 == 0) {
ans += (int)Math.pow(2, i) ;
}
num /= 2;
}
return ans;
}
// Driver code
public static void main(String args[])
{
Integer N = 5;
System.out.println(findComplement((int)N));
}
}
// This code is contributed by Samim Hossain Mondal
Python3
# python3 program to find 1's complement of N.
# Find the 1's complement of N
def findComplement(num):
ans = 0
i = 0
while(True):
if num == 0:
break
ans += pow(2, i) * (not (num % 2))
num //= 2
i += 1
return ans
# Driver code
if __name__ == "__main__":
N = 5
print(findComplement(N))
# This code is contributed by rakeshsahni
C#
// C# code for the above approach
using System;
class GFG
{
// Find the 1's complement of N
static int findComplement(int num)
{
int ans = 0;
for (int i = 0; num > 0; i++) {
if(num % 2 == 0) {
ans += (int)Math.Pow(2, i) ;
}
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(log N)
辅助空间: O(1)