Reputation: 1
I keep getting a runtime error on my submission to the problem at http://www.codechef.com/problems/LASTDIG.
My code is as follows :
public class Main {
public static void main(String[] args) {
try {
Scanner in = new Scanner(System.in);
int i,j;
System.out.println("Enter the no. of test cases - ");
int cases = in.nextInt();
int[][] a = new int[cases][2];
int[] lds = new int[cases];
for(i=0; i<cases; i++) {
for(j=0; j<2; j++) {
a[i][j]=in.nextInt();
}
}
for(j=0; j<cases; j++) {
lds[j] = 0;
int LENGTH = a[j][1] - a[j][0] +1;
int[] arr = new int[LENGTH];
//System.out.printf("%d\n",LENGTH);
int[]sum = new int[LENGTH];
for(i=0; i<LENGTH; i++) {
sum[i] = 0;
arr[i] = a[j][0] + i;
}
for(i=0; i<LENGTH; i++) {
int temp = arr[i];
while(temp !=0 ) {
int r = temp%10;
temp /= 10;
if (r%2 == 0) sum[i] += r*2;
else sum[i] += r;
}
}
for(i=0; i<LENGTH; i++){
lds[j] += sum[i]%10;
}
}
for(i=0; i<cases; i++) {
System.out.printf("%d\n",lds[i]);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Please help me out over here, considering the problem is an easy one.
Thanks !
Upvotes: 0
Views: 350
Reputation: 9708
The code itself runs fine ... given that sensible input is given. For different input, errors could occur like:
So, as the edits try to accomplish, we need to give sensible feedback for unforeseen use cases.
But for the problem in the link, there are other potential issues. Overflow? Overflow will not exist for really large numbers, 2^32 is greater than the largest number, but I do notice that a large integer can give an OutOfMemory error, so I reckon this bit of code comes down to inefficiency and the need for a better algorithm to handle larger integers.
Upvotes: 0