Sum of all substrings of a number
Solution :
Here when we generate table of substring occurrence then this formula is being generated :
initialize 0th index with 0th char.
sumofdigit[i] = (i+1)*num[i] + 10*sumofdigit[i-1]
but this will take extra space
Another approach :
when all the sub strings are converted further to the ones, tens, hundreds .. form, each index of the string will have a some fixed occurrence. The 1st index will have 1 occurrence each of ones, tens etc..The 2nd will have 2, 3rd will have 3 and so on.
One more point is that the occurrence of last element will only be restricted to ones. Last 2nd element will be restricted to ones and tens. Last 3rd will be up to hundred and so on.
From the above points lets find out the sum.
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class hackerranksolutionc
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
String str=new String(ab.next());
long sum=0;
long mf=1;
for(int i=str.length()-1;i>=0;--i)
{
int num=str.charAt(i)-'0';
sum+=num*(i+1)*mf;
mf*=10;
++mf;
}
System.out.println(sum);
}
}
}
Here when we generate table of substring occurrence then this formula is being generated :
initialize 0th index with 0th char.
sumofdigit[i] = (i+1)*num[i] + 10*sumofdigit[i-1]
but this will take extra space
Another approach :
when all the sub strings are converted further to the ones, tens, hundreds .. form, each index of the string will have a some fixed occurrence. The 1st index will have 1 occurrence each of ones, tens etc..The 2nd will have 2, 3rd will have 3 and so on.
One more point is that the occurrence of last element will only be restricted to ones. Last 2nd element will be restricted to ones and tens. Last 3rd will be up to hundred and so on.
From the above points lets find out the sum.
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class hackerranksolutionc
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
String str=new String(ab.next());
long sum=0;
long mf=1;
for(int i=str.length()-1;i>=0;--i)
{
int num=str.charAt(i)-'0';
sum+=num*(i+1)*mf;
mf*=10;
++mf;
}
System.out.println(sum);
}
}
}
0 Comments:
Post a Comment