DEV Community

Ayush Mishra
Ayush Mishra

Posted on

Splitting a Number into Digits

Understanding how to split a number into its individual digits is a fundamental skill in programming. This technique is particularly useful for solving problems like:

By mastering the methods described below, you'll be good to tackle these and similar problems.


1. From First Digit to Last Digit

To extract digits from left to right, we need to isolate the first digit and then work our way down. This is where log10 and powers of 10 come in.

The Formula

d = pow(10, floor(log10(n)))
first_digit = floor(n / d)
Enter fullscreen mode Exit fullscreen mode

So, log10(n) tells you the power to which 10 must be raised to get n.

  • Example: n = 512log10(512) ≈ 2.7
  • This means 10^2.7 ≈ 512.

floor(log10(n)) removes the decimal, leaving just the exponent of the largest power of 10 smaller than n.

  • floor(2.7) = 2 → the largest power of 10 smaller than 512 is 10^2 = 100.

pow(10, k) gives the divisor to scale the number down to a value between 1 and 10.

  • 512 / 100 = 5.12 → take the floor → 5, the first digit.

After getting the first digit, reduce n using modulo: n % d = 512 % 100 = 12 → then repeat with the remaining number.

n = 512
d = 10^2 = 100
First digit: floor(512 / 100) = 5
Remaining: 512 % 100 = 12

Next digit: floor(12 / 10) = 1
Remaining: 12 % 10 = 2

Last digit: 2

// 5,1,2
Enter fullscreen mode Exit fullscreen mode

2. From Last Digit to First Digit

Simpler because modulo handles it directly:

n = 512
512 % 10 = 2
512 // 10 = 51

51 % 10 = 1
51 // 10 = 5

5 % 10 = 5
5 // 10 = 0 → done

/*
Result : 2,1,5
*/ 
Enter fullscreen mode Exit fullscreen mode

the same order. This involves splitting each number into its digits and combining them.

Top comments (0)