Skip to content

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:

Input
54
Output
9
Input
38
Output
55
Input
55
Output
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

def product_of_sum_and_abs_diff_of_digits(num: int):
    num   = abs(num)
    tens  = num // 10
    units = num % 10
    return (tens + units) * abs(tens - units)
def product_of_sum_and_abs_diff_of_digits(num: int):
    num   = abs(num)
    tens  = num // 10
    units = num % 10

    digit_sum  = tens + units
    digit_diff = abs(tens - units)

    return digit_sum * digit_diff
def product_of_sum_and_abs_diff_of_digits(num: int):
    digits = [int(d) for d in str(abs(num))]
    return (digits[0] + digits[1]) * abs(digits[0] - digits[1])

Converts to string to extract digits - works for any number of digits, though floor division is faster for exactly two digits.

product_of_sum_and_abs_diff_of_digits = lambda num: (
    (lambda t, u: (t + u) * abs(t - u))(abs(num) // 10, abs(num) % 10)
)

Key takeaways

01

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.

02

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.

03

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.