# 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 −

Live Demo

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))

20

## Output

11

Updated on: 28-Apr-2020

1K+ Views
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "https://www.tutorialspoint.com/complement-of-base-10-integer-in-python", "fetch_time": 1716565728000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2024-22/segments/1715971058721.41/warc/CC-MAIN-20240524152541-20240524182541-00662.warc.gz", "warc_record_offset": 896029386, "warc_record_length": 24940, "token_count": 268, "char_count": 929, "score": 3.765625, "int_score": 4, "crawl": "CC-MAIN-2024-22", "snapshot_type": "latest", "language": "en", "language_score": 0.6902918219566345, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00013-of-00064.parquet"}