forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_coded_decimal.py
29 lines (26 loc) · 705 Bytes
/
binary_coded_decimal.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
defbinary_coded_decimal(number: int) ->str:
"""
Find binary coded decimal (bcd) of integer base 10.
Each digit of the number is represented by a 4-bit binary.
Example:
>>> binary_coded_decimal(-2)
'0b0000'
>>> binary_coded_decimal(-1)
'0b0000'
>>> binary_coded_decimal(0)
'0b0000'
>>> binary_coded_decimal(3)
'0b0011'
>>> binary_coded_decimal(2)
'0b0010'
>>> binary_coded_decimal(12)
'0b00010010'
>>> binary_coded_decimal(987)
'0b100110000111'
"""
return"0b"+"".join(
str(bin(int(digit)))[2:].zfill(4) fordigitinstr(max(0, number))
)
if__name__=="__main__":
importdoctest
doctest.testmod()