livepython.net

192. Python Program to Reverse the Digits of a Number

EasyPhase 1 · Warm-up

A while loop, % and // are all you need here, and you know all three.

Overview

Reversing the digits of a number is a common interview question. It tests if you can take a number apart, one digit at a time, with maths.

Problem Statement

Kofi plays a number game with friends. A friend says a number, and Kofi says it back with the digits in the opposite order.

Read a whole number and print its digits reversed, as a number: Reversed: <number>.

A number never starts with a zero. So zeros at the end of the input disappear: 1200 gives 21. The number 0 gives 0.

Steps

  1. Read the number and turn it into a whole number.
  2. Start the result at 0.
  3. While the number is more than 0, take its last digit and add it to the end of the result. To add a digit to the end, multiply the result by 10 and add the digit.
  4. Then cut the last digit off the number, and go round again.
  5. Print the result.

Examples

Example 1. Input 1234 gives:

Reversed: 4321

Why: the digits 1, 2, 3, 4 come out in the order 4, 3, 2, 1.

Example 2. Input 1200 gives:

Reversed: 21

Why: reversed, the digits are 0, 0, 2, 1. Zeros at the start of a number do not count, so the number is 21.

Input

One whole number (0 or more). Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line: Reversed: <number>. The tests try 6 different inputs, also 0, 7 and 100.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 11 · While Loops
solution.py
# write your code here

EXPECTED OUTPUT

1Reversed: 4321

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.