Integer to Binary with Variables
Python
Medium
2 views
Problem Description
Read one integer n. Output its binary without using bin(). Use repeated division and variables.
Input Format
One integer n (non-negative).
Output Format
Binary string.
Official Solution
import sys
s=sys.stdin.read().strip()
if not s: sys.exit(0)
n=int(s)
if n==0:
sys.stdout.write('0')
else:
bits=[]
while n>0:
bits.append('1' if n%2 else '0')
n//=2
sys.stdout.write(''.join(reversed(bits)))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!