Sum of digits in the given number.
Write a program to calculate the sum of all the digits of N. N is an integer.
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));
}
}
}
*******************************************************************************
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
Post a Comment