0

Can anybody explain me logic for this code

about reversing number https://code.sololearn.com/c2ywZ802j10s/?ref=app

25th Sep 2018, 4:12 PM
Ishwarendra Jha
3 Answers
+ 1
Here we know what the code is supposed to do, so a good way to approach it is to decompose and identify each part to understand the logic. Variables : n is the initial number, s will receive the reverse number. Loop : s receives s*10 + n%10. So each number in s will move one step on the left and with the addition the last 0 is replaced by the unit number of n (since it is the result the remainder of int div of n by 10). n receives the result of the integer (//) division of n and 10. So the last number of n is removed. Initial step : s starts with 0, so will receive initially the unit number of n. End of loop : when n is a one digit number (which means as we saw in the loop that it was the biggest digit of our initial n), the result of n//10 will be 0 and as such the loop will end. Does that help you ?
25th Sep 2018, 4:40 PM
dhm
+ 1
tl;dr version : in the loop, s receives each time its own numbers moved one time on the left and the last number of n. Then n sees its unit number removed for the next loop (so loses its last number)
25th Sep 2018, 4:42 PM
dhm
+ 1
yes it helped a lot.. thanks
18th Feb 2020, 7:14 AM
Ishwarendra Jha