About Solution

Following is my code for DIgit Sum what is wroung with that

import java.io.*;
import java.util.*;
class DigitSum
{
public static void main(String[]args)
{
DigitSum s1=new DigitSum();
Scanner sc=new Scanner(System.in);
int i=sc.nextInt();
for(int j=0;j<i;j++)
{
int s=sc.nextInt();
int n=s1.sum(s);
System.out.println(n);
}
}
int sum(int n)
{
return(n%10+sum(n/10));
}
}

You sure that s is less than {10}^{9} to be stored in int?

The thing is,

you have made a recursive function without a base case… a fundamental mistake in recursive functions… (although i like your technique :slight_smile: ).

Read more about recursive functions in detail here

change sum function to

if(N==0)return 0;
return (N%10+sum(N/10));

I hope this should help…

Please Upvote and accept if you find this helpful…