Similar Problems
Similar Problems not available
Complement Of Base 10 Integer - Leetcode Solution
LeetCode: Complement Of Base 10 Integer Leetcode Solution
Difficulty: Easy
Topics: bit-manipulation
Problem statement:
Given a positive integer, you have to return its complement with respect to the base 10 representation of it.
Example 1: Input: 5 Output: 2 Explanation: 5 is represented in binary as 101, its complement is 010 which is 2 in base 10.
Example 2: Input: 1 Output: 0 Explanation: 1 is represented in binary as 1, its complement is 0 which is 0 in base 10.
Solution:
The problem can be solved by understanding the concept of binary complement. Complement of a binary number is the bitwise inversion of the number, i.e. 0’s are replaced by 1’s and 1’s are replaced by 0’s.
For example, if the binary representation of a number is 10110, its complement would be 01001.
Now, to find the complement of a number in base 10, we need to convert it to binary first, then find its complement and finally convert it back to base 10.
We can use the following steps to achieve this:
Step 1: Convert the given number to binary representation.
We can use the built-in function bin() in Python to convert the given number to its binary representation.
For example, if the given number is 5, its binary representation would be "0b101". We need to remove the "0b" prefix to get the binary number.
binary = bin(num)[2:]
Step 2: Find the complement of the binary number.
We can use a loop to iterate through each digit of the binary number and replace 0’s with 1’s and 1’s with 0’s.
complement = '' for digit in binary: if digit == '0': complement += '1' else: complement += '0'
Step 3: Convert the complement back to base 10.
We can use the built-in function int() in Python to convert the complement from binary to decimal.
complement = int(complement, 2)
Finally, we return the complement as the output.
Code:
Here is the complete Python code for the solution:
def findComplement(num: int) -> int: binary = bin(num)[2:] complement = '' for digit in binary: if digit == '0': complement += '1' else: complement += '0' complement = int(complement, 2) return complement
Time complexity: O(log n)
Space complexity: O(log n)
Complement Of Base 10 Integer Solution Code
1