There is not just one way to solve a problem. Don't stop thinking about more than one way, think about performance, memory utilization, and efficiency of algorithm design.
public class AddDigits {
private static int EXP=64;
public static void main(String[] args) {
System.out.printf("I added all (1234567) %d: \n",addDigits(1234567));
System.out.printf("I added all (1234567) %d: \n",addDigits("1234567"));
System.out.printf("I added all (1234567) %d: \n",addDigitsRec(1234567));
}
private static long addDigitsRec(long n){
if(n<10){
return n;
}
else{
int index=0;
for(;n/Math.pow(10,index)>9;index++){}
return totalAdd(n,index);
}
}
private static long totalAdd(long n, int index){
long total=(int)(n/Math.pow(10,index));
if(index==0){
return total;
}
else
total+=totalAdd((int)(n%Math.pow(10,index--)),index);
return total;
}
private static long addDigits(long n){
if(n<10){
return n;
}
else{
int index=0,total=0;
for(;n/Math.pow(10,index)>9;index++){}
while(index>-1){
total+=(int)(n/Math.pow(10,index));
n=(int)(n%Math.pow(10,index--));
}
return total;
}
}
private static long addDigits(String n){
if(n.length()==0){
return 0;
}
else{
long total=0;
for(int index=0;index<n.length();index++){
total+=Integer.parseInt(""+n.charAt(index));
}
return total;
}
}
}
No comments:
Post a Comment