🔢 Integer Tricks

Integer Tricks

Digit extraction, reversal, digit sum — via modulo, not string conversion

Working with the digits of an integer using arithmetic is a pattern that appears constantly. Understanding the modulo + floor-division loop unlocks a whole class of problems.

Language:
Python
Loading...

All languages — Split integer into digits

JavaScript
function digits(n) {
  if (n === 0) return [0];
  const result = [];
  while (n > 0) {
    result.push(n % 10);          // last digit
    n = Math.floor(n / 10);       // drop last digit
  }
  return result.reverse();
}

console.log(digits(1234));  // [1, 2, 3, 4]
console.log(digits(900));   // [9, 0, 0]
TypeScript
function digits(n: number): number[] {
  if (n === 0) return [0];
  const result: number[] = [];
  while (n > 0) {
    result.push(n % 10);
    n = Math.floor(n / 10);
  }
  return result.reverse();
}

console.log(digits(1234));  // [1, 2, 3, 4]
Java
import java.util.*;

public static List<Integer> digits(int n) {
    if (n == 0) return List.of(0);
    List<Integer> result = new ArrayList<>();
    while (n > 0) {
        result.add(n % 10);         // last digit
        n /= 10;                    // drop last digit
    }
    Collections.reverse(result);
    return result;
}

// In main:
System.out.println(digits(1234));   // [1, 2, 3, 4]
Go
func digits(n int) []int {
    if n == 0 {
        return []int{0}
    }
    var result []int
    for n > 0 {
        result = append([]int{n % 10}, result...) // prepend
        n /= 10
    }
    return result
}

func main() {
    fmt.Println(digits(1234))  // [1 2 3 4]
}
C++
#include <vector>
#include <algorithm>

vector<int> digits(int n) {
    if (n == 0) return {0};
    vector<int> result;
    while (n > 0) {
        result.push_back(n % 10);
        n /= 10;
    }
    reverse(result.begin(), result.end());
    return result;
}

// digits(1234) → {1, 2, 3, 4}