DSA Factory
Free lessonsProgramming basics · Stage 1 · Numbers · Step 3

Peeling off digits

Read the last digit of a number, and drop it. About 8 minutes.

The last digit

How do you read the last digit of 4721? Your eyes just see it, but the computer sees one number. Think back to the remainder: divide 4721 by 10, and you get 472 with 1 left over.

That leftover is exactly the last digit. So the remainder after dividing by 10 always gives you the last digit of a number, whatever its size.

Remainder by 10: is the last digit.
In code
n = 4721
last = n % 10      # 1
Peeling digits off 4721
4
0
7
1
2
2
1
3
digit
n
4721
last digit
1

Start with 4721. The remainder after dividing by 10 is 1, so the last digit is 1.

Move 1 of 4

Dropping the last digit

The other half of the same division is the 472. Whole-number division by 10 throws away the leftover, and that cuts the last digit off.

Together the two tools take a number apart: use the remainder to read the last digit, then divide to drop it. To read the digit before the last one, drop first and read again. The tens digit of 4721 is the last digit of 472.

Divide by 10: to drop the last digit.
In code
n = 4721
rest = n // 10     # 472
tens = rest % 10   # 2
Quick check

n is 905. What is its last digit, and what is left when you drop it?

  1. ALast digit 5, and 90 is left
  2. BLast digit 9, and 05 is left
  3. CLast digit 5, and 9 is left
Show the answer

Last digit 5, and 90 is left. 905 divided by 10 is 90 with remainder 5.

Your problem

Swap the two digits

You get a two-digit number. Return the number you get when the two digits trade places. If the number ends in zero, the result simply has fewer digits.

Example
n = 47 → 74

10 ≤ n ≤ 99

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding