-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.py
More file actions
43 lines (31 loc) · 854 Bytes
/
binary.py
File metadata and controls
43 lines (31 loc) · 854 Bytes
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
#-----------------------------------------------------------------------
# binary.py
#-----------------------------------------------------------------------
import sys
import stdio
# Accept integer n as a command-line argument. Write the binary
# representation of n to standard output.
# Limitation: Does not handle negative integers.
n = int(sys.argv[1])
# Compute v as the largest power of 2 <= n.
v = 1
while v <= n//2:
v *= 2
# Cast out powers of 2 in decreasing order.
while v > 0:
if n < v:
stdio.write(0)
else:
stdio.write(1)
n -= v
v //= 2
stdio.writeln()
#-----------------------------------------------------------------------
# python binary.py 19
# 10011
# python binary.py 255
# 11111111
# python binary.py 512
# 1000000000
# python binary.py 1000000000
# 111011100110101100101000000000