Find One’s Complement of an Integer | Set 2
Last Updated :
13 Jan, 2022
Given an integer N, find the one’s complement of the integer.
Examples:
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
Approach: Already the XOR-based approach and converting the number to binary number approaches are mentioned in Set-1 of the article. Here the number is converted by flipping bits and adding that power of 2 to the answer. Follow the steps mentioned below to implement it:
- Find the binary representation of N.
- For each bit, complement it and add the contribution of this bit to the final answer.
- Return the final answer
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int findComplement( int num)
{
int ans = 0;
for ( int i = 0; num > 0; i++) {
ans += pow (2, i) * (!(num % 2));
num /= 2;
}
return ans;
}
int main()
{
unsigned int N = 5;
cout << findComplement(N);
return 0;
}
|
Java
import java.util.*;
public class GFG
{
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;
}
public static void main(String args[])
{
Integer N = 5 ;
System.out.println(findComplement(( int )N));
}
}
|
Python3
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
if __name__ = = "__main__" :
N = 5
print (findComplement(N))
|
C#
using System;
class GFG
{
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;
}
public static void Main()
{
uint N = 5;
Console.Write(findComplement(( int )N));
}
}
|
Javascript
<script>
function findComplement(num) {
let ans = 0;
for (let i = 0; num > 0; i++) {
ans += Math.pow(2, i) * (!(num % 2));
num = Math.floor(num / 2);
}
return ans;
}
let N = 5;
document.write(findComplement(N));
</script>
|
Time Complexity: O(log N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...