Coding problem · Easy · Basics
Sum of Digits
Easy Algorithms & data structures
Return the sum of the digits of the non-negative integer n.
Example 1
Input: n = 1234 Output: 10
Example 2
Input: n = 0 Output: 0
Hints
Hint 1
n % 10 is the last digit; integer division by 10 removes it.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(digits) · Space O(1)
Repeatedly add n % 10 and divide n by 10 (integer division) until it reaches 0. Converting to a string and adding characters also works.
Reference solution
function sumOfDigits(n) {
let total = 0;
while (n > 0) { total += n % 10; n = Math.floor(n / 10); }
return total;
}
function sumOfDigits(n: number): number {
let total = 0;
while (n > 0) { total += n % 10; n = Math.floor(n / 10); }
return total;
}
def sum_of_digits(n: int) -> int:
return sum(int(ch) for ch in str(n))
<?php
function sumOfDigits(int $n): int
{
return array_sum(str_split((string) $n));
}
class Solution {
public int sumOfDigits(int n) {
int total = 0;
while (n > 0) { total += n % 10; n /= 10; }
return total;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy