Skip to content

Commit e313141

Browse files
syedwaleedhydercclauss
authored andcommitted
bin(num). convert ZERO and negative decimal numbers to binary. (TheAlgorithms#1093)
* bin(num) can convert ZERO and negative decimal numbers to binary. Consistent with built-in python bin(x) function. * bin(num) can convert ZERO and negative decimal numbers to binary. Consistent with built-in python bin(x) function. * Added doctests. bin(num) can convert ZERO and negative decimal numbers to binary. Consistent with built-in python bin(x) function. * Added doctests. bin(num) can convert ZERO and negative decimal numbers to binary. Consistent with built-in python bin(x) function. * Added doctests. bin(num) can convert ZERO and negative decimal numbers to binary. Consistent with built-in python bin(x) function. * doctests still failing. * Doctests added.
1 parent 9c0cbe3 commit e313141

File tree

1 file changed

+46
-13
lines changed

1 file changed

+46
-13
lines changed

conversions/decimal_to_binary.py

+46-13
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,57 @@
22

33

44
def decimal_to_binary(num):
5-
"""Convert a Decimal Number to a Binary Number."""
5+
6+
"""
7+
Convert a Integer Decimal Number to a Binary Number as str.
8+
>>> decimal_to_binary(0)
9+
'0b0'
10+
>>> decimal_to_binary(2)
11+
'0b10'
12+
>>> decimal_to_binary(7)
13+
'0b111'
14+
>>> decimal_to_binary(35)
15+
'0b100011'
16+
>>> # negatives work too
17+
>>> decimal_to_binary(-2)
18+
'-0b10'
19+
>>> # other floats will error
20+
>>> decimal_to_binary(16.16) # doctest: +ELLIPSIS
21+
Traceback (most recent call last):
22+
...
23+
TypeError: 'float' object cannot be interpreted as an integer
24+
>>> # strings will error as well
25+
>>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS
26+
Traceback (most recent call last):
27+
...
28+
TypeError: 'str' object cannot be interpreted as an integer
29+
"""
30+
31+
if type(num) == float:
32+
raise TypeError("'float' object cannot be interpreted as an integer")
33+
if type(num) == str:
34+
raise TypeError("'str' object cannot be interpreted as an integer")
35+
36+
if num == 0:
37+
return "0b0"
38+
39+
negative = False
40+
41+
if num < 0:
42+
negative = True
43+
num = -num
44+
645
binary = []
746
while num > 0:
847
binary.insert(0, num % 2)
948
num >>= 1
10-
return "".join(str(e) for e in binary)
1149

50+
if negative:
51+
return "-0b" + "".join(str(e) for e in binary)
1252

13-
def main():
14-
"""Print binary equivelents of decimal numbers."""
15-
print("\n2 in binary is:")
16-
print(decimal_to_binary(2)) # = 10
17-
print("\n7 in binary is:")
18-
print(decimal_to_binary(7)) # = 111
19-
print("\n35 in binary is:")
20-
print(decimal_to_binary(35)) # = 100011
21-
print("\n")
53+
return "0b" + "".join(str(e) for e in binary)
2254

2355

24-
if __name__ == '__main__':
25-
main()
56+
if __name__ == "__main__":
57+
import doctest
58+
doctest.testmod()

0 commit comments

Comments
 (0)