

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- 10’s Complement of a decimal number?
- Base 3 to integer in Python
- Integer to Base 3 Number in Python
- Compute the logarithm base 10 with scimath in Python
- Find One’s Complement of an Integer in C++
- How to get base 10 logarithms of E in JavaScript?
- Get the base 10 logarithm of a value in Java
- Complement of Graph
- Convert the string of any base to integer in JavaScript
- Return the base 10 logarithm of the input array element-wise in Numpy
- How to convert a string of any base to an integer in JavaScript?
- 1's Complement vs 2's Complement
- How to create a column of log with base 10 in data frames stored in R list?
- 10 Interesting Python Cool Tricks
- Interpreter base classes in Python
Advertisements