I am new to CodeChef and I am trying to solve this problem http://www.codechef.com/problems/CHEFA
My code works pretty well in my PC but Shows NZEC Runtime when i try to run. I have Tried EVERYTHING possible including Adding numbers USING STRING so that its not out of constraint here is my code :
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
class MyProgram{
public static void main(String[] s){
Scanner scan = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
int numTest = Integer.parseInt(scan.nextLine());
if(numTest < 0)
System.exit(0);
String[] myNumPiles = new String[numTest];
int[] numPiles = new int[numTest];
String[] maxPile = new String[numTest];
String[] numStones = new String[numTest];
for(int i = 0; i<numTest ; ++i){
myNumPiles[i] = scan.nextLine();
if(myNumPiles[i].equals("0")){
System.out.println("0");
continue;
}
numStones[i] = scan2.nextLine();
}
for(int i = 0; i<numTest ; ++i){
numPiles[i] = Integer.parseInt(myNumPiles[i]);
}
ArrayList<Integer> sorting = new ArrayList<Integer>();
for(int i = 0; i < numTest ; ++i){
String[] tokens = null;
maxPile[i] = "0";
if(numPiles[i] == 0){
continue;
}
tokens = numStones[i].split(" ");
for(String my : tokens){
sorting.add(Integer.parseInt(my));
}
Collections.sort(sorting);
for(int j=sorting.size()-1 ; j>=0 ; j=j-2){
maxPile[i] = myStringWayToAdd(sorting.get(j)+"",maxPile[i]);
}
sorting.clear();
}
//end of for i
for(int i=0 ; i<numTest ; ++i)
System.out.println(maxPile[i]);
}
//Adding numbers using String
public static String myStringWayToAdd(String first , String second){
String temp = "";
if(first.length() < second.length()){
temp = first;
first = second;
second = temp;
}
temp = "";
int carry = 0;
for(int i=1;i<=first.length();++i){
if(i <= second.length()){
carry += Integer.parseInt(first.charAt(first.length()-i)+"") + Integer.parseInt(second.charAt(second.length()-i)+"");
}
else{
carry += Integer.parseInt(first.charAt(first.length()-i)+"");
}
temp += carry%10;
carry = carry/10;
}
if(carry != 0)
temp += carry;
StringBuilder myResult = new StringBuilder(temp);
return(myResult.reverse().toString());
}
}
Can Anyone Please tell me what is wrong with my code here?
Also I saw Some C++ Solutions which was way smaller than my code run successfully , I am asking this because I want to know whether C++ is better than java in these questions or not?
Thank you in Advance