Digits & number tricks
Questions about the digits of a number come in two flavours.
Arithmetic. n % 10 is the last digit and n // 10 removes it. Peel digits off one at a time:
last = n % 10 n = n // 10
Text. str(n) turns the number into a string of digit characters. You can loop over it, slice it, count in it, and turn pieces back with int(...). This is usually the shortest way:
s = str(4072) int(s[1:]) # 72, and int() drops leading zeros s.count("7") # 1
Pick text when you need to look at digits or remove one; pick arithmetic when you add column by column (carries!).
Watch for 0: a loop while n > 0 never runs for n = 0, though 0 has one digit.
Watch n shrink while last collects the digits from the right.
See it run
n = 4072 last = n % 10 n = n // 10 last = n % 10 n = n // 10
n % 10 reads the last digit, n // 10 drops it.
Practice digits & number tricks
Exercise 1
A counter on a gate shows a whole number n. Write solution(n, d) returning how many times the digit d appears in the written form of n.
Rules:
nis zero or more.dis a single digit from 0 to 9.- The number
0is written with one digit:0.
Constraints: 0 ≤ n ≤ 10^18.
Example: solution(1220, 2) returns 2.
Exercise 2
When you add two numbers by hand, column by column from the right, a carry happens whenever a column's total (including any carry from the previous column) is 10 or more. Write solution(a, b) returning how many carries happen when adding a and b.
Rules:
aandbare zero or more and may have different numbers of digits (missing digits count as 0).- A carry out of the leftmost column counts as one carry.
Constraints: 0 ≤ a, b ≤ 10^18.
Example: solution(99, 1) returns 2: 9+1 carries, then 9+0+1 carries again.
Exercise 3
A serial number n has at least two digits. You must delete exactly one digit from it. Return the largest whole number you can get.
Rules:
- Delete one digit anywhere (first, last or in the middle); the other digits keep their order.
- If the result starts with zeros, they simply vanish as in any whole number: deleting the 1 from
1000leaves000, which is0. - Return an integer.
Constraints: 10 ≤ n ≤ 10^18.
Example: solution(1203) returns 203, better than 103, 123 or 120.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.