Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Smallest & Largest Digit

Track the smallest and largest digits with Python. Students update two running extremes, handle negative magnitudes, and treat zero as a real digit.

AdvancedPhase 2 - Level 5: Logical Loop CombinationsExample 5 of 12
smallest-largest-digit.py
1# Take number
2num = int(input("Enter a number: "))
3
4# Find smallest and largest digit
5temp = abs(num)
6smallest = 0 if temp == 0 else 9
7largest = 0
8
9while temp > 0:
10 digit = temp % 10
11 if digit < smallest:
12 smallest = digit
13 if digit > largest:
14 largest = digit
15 temp //= 10
16
17print(f"Smallest digit: {smallest}")
18print(f"Largest digit: {largest}")

Output

Enter a number: 45231
Smallest digit: 1
Largest digit: 5

In this one

  • Track two extremes
  • Choose decimal sentinels
  • Handle zero input

How it works

  1. 1

    Set initial smallest with the zero case and largest zero.

  2. 2

    Compare each extracted digit against both extremes.

  3. 3

    Remove the digit and report the final pair.

Edge cases

What are both extremes for zero?

What are both extremes for zero?

Both should be zero.

What about -482?

What about -482?

abs makes its digits equivalent to 482.

What's going on

smallest starts at nine and largest at zero, the extremes of decimal digit values. Each extracted digit can replace either stored extreme.

For 482, the minimum becomes two and maximum eight. abs removes a negative sign before scanning. Zero needs explicit treatment because the loop is skipped; leaving smallest at nine would report a digit that was never present.

What are both extremes for zero? Both should be zero.

What about -482? abs makes its digits equivalent to 482.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why initialize smallest to nine?

Pick an answer to check it.

Question 2

What are both extremes for zero?

Pick an answer to check it.

Questions people ask

What are both extremes for zero?

Both should be zero.

What about -482?

abs makes its digits equivalent to 482.

Why initialize smallest to nine?

Every decimal digit can be no greater than nine.