S1Q1 · Product of Sum and Absolute Difference of Digits¶
⚡ Quick Reference
Function: product_of_sum_and_abs_diff_of_digits(num: int) -> int
Core idea: extract tens and units digits, compute sum and absolute difference, return their product.
def product_of_sum_and_abs_diff_of_digits(num: int):
num = abs(num) # handle negative two-digit numbers
tens = num // 10
units = num % 10
return (tens + units) * abs(tens - units)
Key rules:
- Tens digit: num // 10
- Units digit: num % 10
- Result: (tens + units) × |tens − units|
- If both digits are equal → absolute difference = 0 → product = 0
Problem Statement¶
Problem
Write a function product_of_sum_and_abs_diff_of_digits(num) that returns the product of the sum and absolute difference of the two digits of a two-digit number.
Examples:
54
9
38
55
55
0
Tracing all examples¶
num |
tens | units | sum | abs diff | product |
|---|---|---|---|---|---|
| 54 | 5 | 4 | 9 | |5−4| = 1 | 9 × 1 = 9 ✓ |
| 38 | 3 | 8 | 11 | |3−8| = 5 | 11 × 5 = 55 ✓ |
| 55 | 5 | 5 | 10 | |5−5| = 0 | 10 × 0 = 0 ✓ |
Solution approaches¶
Key takeaways¶
num // 10 and num % 10 extract the two digits
For any two-digit number, integer division by 10 gives the tens digit and the remainder gives the units digit. Fast, clean, and needs no string conversion.
Equal digits → product is zero
When both digits are the same (e.g. 55), the absolute difference is 0. Multiplying anything by 0 gives 0 - no special case needed; the formula handles it naturally.
abs() on the number handles negatives
For a negative two-digit number like -54, abs(-54) = 54 gives the correct digits. Always apply abs() before extracting digits to avoid negative remainders.