The challenge

Find the number with the most digits in a list of positive integers. If two numbers have the same number of digits, return the first one that appears in the array.

Examples:

find_longest([1, 10, 100])     # → 100
find_longest([9000, 8, 800])   # → 9000
find_longest([8, 900, 500])    # → 900

Solution 1: using max() with a key function

The cleanest approach — max() with a custom key that counts digits:

def find_longest(arr):
    return max(arr, key=lambda x: len(str(x)))

Why this works: max() returns the first maximum element it encounters when there are ties, which satisfies the “return the first one” requirement. Converting to string and measuring length gives the digit count.

Solution 2: manual iteration (no built-in max)

If you can’t use max():

def find_longest(arr):
    longest = arr[0]
    longest_digits = len(str(arr[0]))

    for num in arr[1:]:
        digits = len(str(num))
        if digits > longest_digits:
            longest = num
            longest_digits = digits

    return longest

Why this works: We track the current winner and only replace it when we find a strictly longer number. Using > (not >=) ensures we keep the first occurrence on ties.

Solution 3: using math instead of string conversion

Avoid converting to strings entirely:

import math

def find_longest(arr):
    return max(arr, key=lambda x: math.floor(math.log10(x)) + 1 if x > 0 else 1)

math.log10(x) gives the number of digits minus one (e.g., log10(100) = 2, and 100 has 3 digits). This avoids string allocation for very large numbers.

Edge cases to consider

  • Single-element list: return that element
  • All numbers have the same digit count: return the first
  • Very large numbers (10^20+): all solutions handle these, but the math approach avoids creating large strings

Test cases

assert find_longest([1, 10, 100]) == 100
assert find_longest([9000, 8, 800]) == 9000
assert find_longest([8, 900, 500]) == 900
assert find_longest([3, 40000, 100]) == 40000
assert find_longest([1, 200, 100000]) == 100000

Looking for more Python puzzles that work with numbers and lists?