Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Fixed problem representing 0 wrong
  • Loading branch information
Leyza committed Dec 27, 2020
commit ec0fe34ffcb014949ba707293423e6eb032db74f
9 changes: 6 additions & 3 deletions bit_manipulation/binary_twos_complement.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ def twos_complement(a: int) -> str:
Take in a negative integer 'a'.
Return the two's complement representation of 'a'.

>>> twos_complement(0)
'0b0'
>>> twos_complement(-1)
'0b11'
>>> twos_complement(-5)
Expand All @@ -18,9 +20,10 @@ def twos_complement(a: int) -> str:
"""
if a > 0:
raise ValueError("input must be a negative integer")
bit_a_length = len(bin(a)[3:])
twos_complement_a = bin(abs(a) - (1 << bit_a_length))[3:]
twos_complement_a = '1' + '0' * (bit_a_length - len(twos_complement_a)) + twos_complement_a
binary_a_length = len(bin(a)[3:])
twos_complement_a = bin(abs(a) - (1 << binary_a_length))[3:]
twos_complement_a = ('1' + '0' * (binary_a_length - len(twos_complement_a)) +
twos_complement_a) if a < 0 else '0'
return '0b' + twos_complement_a


Expand Down