- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Complement of Base 10 Integer in Python
Suppose we have a number in decimal number system. We have to get the complement of the number in binary form, then again change it to decimal and return the result. So if the number is 20, then the binary form will be 10100, the complement will be 01011, this is 11 in decimal
To solve this, we will follow these steps −
- s := binary string of the number n
- sum := 0 and num := 1
- for each element i in s in reverse direction
- if i = ‘b’, then return sum
- otherwise when i = ‘0’, then sum := sum + num
- num := num * 2
Example
Let us see the following implementation to get better understanding −
class Solution(object): def bitwiseComplement(self, N): s = str(bin(N)) sum = 0 num = 1 for i in s[::-1]: if i == "b": return sum elif i =="0": sum+=num num*=2 ob1 = Solution() print(ob1.bitwiseComplement(20))
Input
20
Output
11
- Related Articles
- Base 3 to integer in Python
- Find One’s Complement of an Integer in C++
- Integer to Base 3 Number in Python
- 10’s Complement of a decimal number?
- Compute the logarithm base 10 with scimath in Python
- Convert the string of any base to integer in JavaScript
- Complement of Graph
- Get the base 10 logarithm of a value in Java
- How to get base 10 logarithms of E in JavaScript?
- How to convert a string of any base to an integer in JavaScript?
- An angle is ( 10^{circ} ) more than its complement, find the angle.
- Check if one of the numbers is one’s complement of the other in Python
- Reverse Integer in Python
- If an angle differ from its complement by $10^o$, find the angle.
- One’s Complement

Advertisements