Practice › Basics
Sum of Digits
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Print the sum of the digits of the non-negative integer n.
Input
One integer n.
Output
The digit sum.
Constraints
- 0 ≤ n ≤ 10^18
Example 1
Input
1234
Output
10
Example 2
Input
0
Output
0
Hints
- n % 10 is the last digit; n / 10 drops it.
- Add the last digit to a running sum until n becomes 0. Use a 64-bit type for n.
Approach
Repeatedly add n % 10 to the sum and divide n by 10. The loop runs once per digit. Reading the number as a string and adding each character's digit value works just as well.
Complexity: O(number of digits) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
cout << sum << "\n";
return 0;
}Python solution
s = input().strip()
print(sum(int(ch) for ch in s))Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
System.out.println(sum);
}
}