Today we will be solving Sum of Digits CodeChef Problem in Python,Java and C++ whose code is FLOW006.
Problem
You’re given an integer N. Write a program to calculate the sum of all the digits of N.
Input
The first line contains an integer T, the total number of test cases. Then follow T lines, each line contains an integer N.
Output
For each test case, calculate the sum of digits of N, and display it in a new line.
Constraints
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 1000000
Example
Input
3
12345
31203
2123
Output
15
Solution – Sum of Digits CodeChef Solution
Python
#Solution provided by Sloth Coders n = int(input()) for _ in range(n): num = input() sum = 0 for i in num: sum += int(i) print(sum)
Java
import java.io.*; public class Main { private static void digitSum() throws IOException { int digit,sum; final BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); final int t = Integer.parseInt(br.readLine()); for(int i=0 ; i<t ;i++) { sum = 0; final int n = Integer.parseInt(br.readLine()); int temp = n; for( ;temp>0 ; temp=temp/10) { digit = temp%10; sum+=digit; } System.out.println(sum); } } public static void main(String[] args) throws IOException{ // TODO Auto-generated method stub digitSum(); } }
C++
#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; while(n--) { int num,m,sum=0; cin>>num; while(num>0) { m=num%10; sum+=m; num/=10; } cout<<sum<<"\n"; } return 0; }
Disclaimer: The above problem (Sum of Digits :FLOW006) is generated by CodeChef but the Solution is provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.
Broz Who Code
CodingBroz