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:
- LeetCode 258: Add Digits
- LeetCode 2520. Count the Digits That Divide a Number
- LeetCode 3701: Compute Alternating Sum
- LeetCode 2544: Alternating Digit Sum
- LeetCode 2553: Separate the Digits in an Array
- LeetCode 2535: Difference Between Element Sum and Digit Sum of an Array
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)
So, log10(n)
tells you the power to which 10 must be raised to get n
.
- Example:
n = 512
→log10(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 is10^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
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
*/
the same order. This involves splitting each number into its digits and combining them.
Top comments (0)