LeetCode

Odd Numbers

Custom
November 20, 2025 · Math

Problem

Given a number n, return the sum of the last digits of the first n odd numbers.

The last digits of the odd numbers cycle in a fixed pattern: 1, 3, 5, 7, 9, 1, 3, 5, 7, 9, .... For n = 7 the odd numbers are 1, 3, 5, 7, 9, 11, 13, their last digits are 1, 3, 5, 7, 9, 1, 3, and the answer is 29.

Solution

There is no need to generate the odd numbers at all. The last digits repeat in a cycle of 5 (1 + 3 + 5 + 7 + 9 = 25), so:

  1. Every complete cycle of 5 odd numbers contributes exactly 25.
  2. Math.floor(n / 5) full cycles contribute q * 25.
  3. The remaining n % 5 numbers take the first r values of the cycle.
const sumLastDigitsOdd = (n: number): number => {
  const cycle = [1, 3, 5, 7, 9];
  const q = Math.floor(n / 5);
  const r = n % 5;

  let result = q * 25;

  for (let i = 0; i < r; i++) {
    result += cycle[i];
  }

  return result;
};

Complexity Analysis

Measure Complexity
Time Complexity O(1)
Space Complexity O(1)

Notes