Given a base 10 integer N, the task is to find the 1’s complement of this Base 10 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
Approach: 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, flip 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
class GFG {
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;
}
public static void main(String[] args)
{
int N = 5 ;
System.out.print(findComplement(( int )N));
}
}
|
Python
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;
if __name__ = = '__main__' :
N = 5 ;
print (findComplement(N));
|
C#
using System;
class GFG
{
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;
}
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(logN)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
17 Jan, 2022
Like Article
Save Article