CodeChef - Sum of Digits

Sum of Digits problem from CodeChef.

CodeChef - Sum of Digits

Problem

You're given an integer N. Write a program to calculate the sum of all the digits of N.

Input Format

The first line contains an integer T, the total number of test cases. Then follow T lines, each line contains an integer N.

Output Format

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

Solution in Java:

import java.util.*;
class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        
        int T = sc.nextInt();
        
        while(T-- > 0){
            long l = sc.nextLong();
            long sum = 0;
            
            while(l != 0){
                sum += l % 10;
                l /= 10;
            }
            System.out.println(sum);
        }
    }
}