Skip to content
Katabench
Try free

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.

The memory bar

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

C#
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.

C# coding challenges →

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