Sum of digits in the given number.

Write a program to calculate the sum of all the digits of N. N is an integer.

Input

The first line contains an integer T, the total number of testcases. 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
9
8

Solution:
 C++:

#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int t;
    cin>>t;
   
    for(int i=0; i<t; i++)
    {
        int n;
        cin>>n;
   
    int sum=0;
   
    while(n>0)
    {
        sum+=n%10;
        n/=10;
    }
   
    cout<<sum<<endl;
    }
    return 0;
}

******************************************************************************
JAVA:

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
   
    static int sum (int n){
        if (n == 0){
            return 0 ;
        }
        return n % 10 + sum(n/10) ;
    }
   
   
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while(t-->0){
            int n = sc.nextInt();
           
            System.out.println(sum(n));
           
        }
    }
}

 *******************************************************************************

Comments

Popular posts from this blog

Priority Scheduling Algorithm Java Program.

Implement UNIX system calls like ps, fork, join, exec family, and wait for process management (use shell script/ Java/ C programming).

Implement a class CppArray which is identical to a one-dimensional C++ array (i.e., the index set is a set of consecutive integers starting at 0) except for the following : 1. It performs range checking. 2.It allows one to be assigned to another array through the use of assignment operator. 3.It supports a function that returns the size of the array.