Given a number n we need to find the sum of it's digit until it becomes single digit and expected time complexity O(1).
Input:- 12345
Output- 6
Solution 1:- Brute Force
import java.util.*;
class GFG {
static int getSum(int n)
{
int sum=0;
while(n>0||sum>9)
{
if(n==0)
{
n=sum;
sum=0;
}
sum+=n%10;
n=n/10;
}
return sum;
}
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println(getSum(n));
}
}
Solution 2:- Best Way
import java.util.*;
class GFG {
static int getSum(int n)
{
if(n==0)
return n;
return (n%9==0?9:n%9);
}
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println(getSum(n));
}
}
Time Complexity- O(1)
Input:- 12345
Output- 6
import java.util.*;
class GFG {
static int getSum(int n)
{
int sum=0;
while(n>0||sum>9)
{
if(n==0)
{
n=sum;
sum=0;
}
sum+=n%10;
n=n/10;
}
return sum;
}
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println(getSum(n));
}
}
import java.util.*;
class GFG {
static int getSum(int n)
{
if(n==0)
return n;
return (n%9==0?9:n%9);
}
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println(getSum(n));
}
}
Time Complexity- O(1)