Sum of Digits
Easy About 10 min Free, no account needed
Sum every digit of every number, without allocating along the way.
The brief
Given an array of non-negative integers numbers, return the sum of all
decimal digits across every number.
For [12, 345] the answer is 1 + 2 + 3 + 4 + 5 = 15.
This puzzle is not about speed, the obvious approach is plenty fast. It is about allocations.
The obvious approach calls n.ToString() for every number. Each call allocates a new
string on the managed heap, so an input of 200,000 numbers allocates megabytes of
garbage. The hidden test measures the bytes your code allocates and fails
anything over a strict 64 KB budget.
Keep DigitSum correct while allocating (almost) nothing. Watch out for hidden
allocators too: LINQ chains, iterator methods, and boxing.
Starter code
using System;
public class Solution
{
// TODO: return the sum of all decimal digits across every number.
public long DigitSum(int[] numbers)
{
throw new NotImplementedException();
}
}How it is graded
Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.
Related guides
What it practices
- Math and number theory
- Replace enumeration with a formula: GCD, modular arithmetic, digit math and closed-form counting.
- Allocation-free code
- Avoid per-item strings and copies with spans, indexes and arithmetic in hot loops.
Related katas
- Add Binary Strings Easy Free Add two binary numbers far too long for any built-in integer.
- Base64 Decoded Length Easy Free The decoded size is pure arithmetic - no need to decode.
- Count Missing Sample Runs Easy Free Count every contiguous interval with no recorded sample, even when the timeline is too large to expand.
- Count Words Easy Free Count words by spotting boundaries, not by splitting.