Sum the digits of an integer
Add the decimal digits of an integer. Ignore the sign when the value is negative.
Course progress
Problem 14 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
number = -4827
Expected output
21
What is happening?
Ignore the negative sign and add the decimal digits: 4 + 8 + 2 + 7 = 21.
Solution strategy
Build the right mental model
Convert the value to a non-negative long, repeatedly take the final digit with modulo 10, then remove that digit with integer division.
Core concepts
modulo · loops
Complexity
Time O(d), space O(1), where d is the number of digits.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for sum-digits
using System;
class Program
{
static int SumDigits(int number)
{
long remaining = Math.Abs((long)number);
int total = 0;
do
{
total += (int)(remaining % 10);
remaining /= 10;
} while (remaining > 0);
return total;
}
static void Main()
{
Console.WriteLine(SumDigits(-4827));
}
}Knowledge check
Questions students often ask
What is the main idea behind sum the digits of an integer?
Convert the value to a non-negative long, repeatedly take the final digit with modulo 10, then remove that digit with integer division.
What is the time and space complexity of this solution?
Time O(d), space O(1), where d is the number of digits.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.