1

First of all, stdio module is just used to call stdio.write() function that is exactly same as print() function in python.

What makes me dizzy in understanding this code is this part. "while v > 0:" For my short point of view, v value never drops down below zero. So for me it looks infinite loop that doesn't stop. v will be halved in sequence. but it never go under zero for my opinion. So, i thought if i give 5 as a input value to this program, than this program would behave and yield the result like "1010000000..." but this program drives right answer "101" which is right binary code for decimal number 5. What am i missing ?

import sys
import stdio

n = int(sys.argv[1])

v = 1
while v <= n // 2:
    v *= 2

print(v)


while v > 0:
    if n < v:
        stdio.write(0)
    else:
        stdio.write(1)
        n -= v
    v //= 2
stdio.writeln()
user290833
  • 11
  • 1

2 Answers2

0

It doesn't go below zero (i.e., negative), but it does drop to 0. Namely, //= truncates any fractional component, meaning 1 // 2 evaluates to 0. When v is 1 halving it yields 0 and the loop ends.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

This is because v is not simply divided by 2, it is divided with no remainder, which is denoted by v //= 2. // means divide with no remainder in Python, while / is the normal division.

For example, if v = 2, then

v //= 2
print(v)  # 1
v //= 2
print(v)  # 0, end of your while loop
W. Ding
  • 587
  • 4
  • 15