binary2.py


Below is the syntax highlighted version of binary2.py from §1.3 Conditionals and Loops.


#-----------------------------------------------------------------------
# binary2.py
#-----------------------------------------------------------------------

import stdio
import sys

# Accept an integer command-line argument n. Place the binary
# representation of n into a string. Then write the string to
# standard output.

# Limitation: Does not handle negative integers.

n = int(sys.argv[1])

if n == 0:
    stdio.writeln(0)
else:
    # Repeatedly divide by two, and form the remainders backwards.
    s = ''
    while n > 0:
        s = str(n % 2) + s
        n //= 2

    stdio.writeln(s)
    
#-----------------------------------------------------------------------

# python binary2.py 19
# 10011

# python binary2.py 255
# 11111111

# python binary2.py 512
# 1000000000

# python binary2.py 1000000000
# 111011100110101100101000000000


Copyright © 2000–2015, Robert Sedgewick, Kevin Wayne, and Robert Dondero.
Last updated: Fri Oct 20 20:45:16 EDT 2017.