forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecimal_to_binary.py
46 lines (36 loc) · 983 Bytes
/
decimal_to_binary.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""
Author :- mehul-sweeti-agrawal
Task :- Given a positive decimal integer, convert it to binary
Input - 9
Output - 1001
"""
def convert_to_binary(number: int) -> int:
"""
Returns binary equivalent of a decimal number
>>> convert_to_binary(8)
1000
>>> convert_to_binary(5)
101
>>> convert_to_binary(-3)
Traceback (most recent call last):
...
ValueError: number must be non-negative
>>> convert_to_binary(9.8)
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for &: 'float' and 'int'
"""
# For negative numbers
if number < 0:
raise ValueError("number must be non-negative")
power = 1 # helper variable
ans = 0 # stores binary equivalent of decimal number
while number:
if number & 1:
ans += power
power *= 10
number >>= 1
return ans
if __name__ == "__main__":
import doctest
doctest.testmod()