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: 0Input: 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++
// CPP program to find 1's complement of N. #include <bits/stdc++.h> 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
<script> // JavaScript code for the above approach // Find the 1's complement of N 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; } // Driver code let N = 5; document.write(findComplement(N)); // This code is contributed by Potta Lokesh </script> |
2
Time Complexity: O(log N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!