Reversing a number — Pseudocode Aptitude Question
Reversing a number: / is integer division and MOD is the remainder. What is printed? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 75 seconds
Question
/ is integer division and MOD is the remainder. What is printed?
Integer n, r
Set n = 4021
Set r = 0
While n > 0
Set r = r * 10 + (n MOD 10)
Set n = n / 10
End While
Print rOptions
- 1204
- 1240
- 4021
- 12040
Show the answer and the worked solution
Correct answer: A. 1204
Worked solution
- First round: r = 0 * 10 + 1 = 1, n = 402.
- Second round: r = 1 * 10 + 2 = 12, n = 40.
- Third round: r = 12 * 10 + 0 = 120, n = 4.
- Fourth round: r = 120 * 10 + 4 = 1204 and n = 0, so the loop ends and 1204 is printed.
Answer: 1204.
The idea
Peel the last digit with MOD 10, drop it with / 10, and build the answer as r * 10 + digit. The interior zero is the detail worth checking, since it contributes nothing visible until a later digit shifts it along.
Shortcut. r = r × 10 + last digit is digit reversal, so write 4021 backwards: 1204, with the interior 0 staying in the middle.
Common trap. 1240 comes from reversing only the non-zero digits (4 2 1 → 1 2 4) and tacking the zero on the end, as if a 0 digit added nothing where it stood.