Description

Sometimes you want a specific digit of an int. Converting to a string is O(n) and hurts runtime.
?
log10(abs(n)) gives the number of digits minus 1, so you can pull any digit directly with division + modulo — O(1).

Reach for when

You need a specific digit (or the digit count) of an integer without the O(n) cost of converting it to a string.

Runtime

O(1)

Visualization

Pseudocode

msb = floor(log10(abs(n)))          # index of the most-significant digit
digit_at(n, i) = (n // 10^(msb - i)) % 10

Code

import math

def digit_at(n, i):
    msb = int(math.log10(abs(n)))    # number of digits - 1
    return (abs(n) // 10 ** (msb - i)) % 10