- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathint2binary.py
More file actions
Latest commit
71 lines (56 loc) · 1.4 KB
/
Copy pathint2binary.py
File metadata and controls
71 lines (56 loc) · 1.4 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
Task:
Converting decimal numbers to binary numbers
>>> convert_to_binary(25)
'0b11001'
>>> convert_to_binary(233)
'0b11101001'
>>> convert_to_binary(42)
'0b101010'
>>> convert_to_binary(0)
'0b0'
>>> convert_to_binary(1)
'0b1'
"""
# Solution 1:
# keep dividing by 2, store the remainder in a stack
# read in reverse order
defconvert_to_binary(number):
ifnumber==0:
return'0b0'
stack= []
whilenumber:
stack.append(number%2)
number=number//2
binary_str="0b"
whilestack:
binary_str+=str(stack.pop())
returnbinary_str
# Solution 2: using built-in function bin
defconvert_to_binary(number):
returnbin(number)
# Solution 3: using string formatting
defconvert_to_binary(number):
return'0b{:b}'.format(number)
# Solution 4: using bitwise operation
defconvert_to_binary(number):
ifnumber==0:
return'0b0'
stack= []
whilenumber:
stack.append(number&1) # append last bit
number=number>>1# remove last bit
binary_str="0b"
whilestack:
binary_str+=str(stack.pop())
returnbinary_str
# Solution 5: using recursion
defconvert_to_binary(number):
digit="01"
ifnumber<2:
return"0b"+digit[number]
else:
returnconvert_to_binary(number//2) +digit[number%2]
if__name__=='__main__':
importdoctest
doctest.testmod()