import java.util.Scanner;
public class JPA407 {
static Scanner keyboard = new Scanner(System.in);
public static void main(String args[]) {
String s;
System.out.print("Input a string of numbers: ");
s = keyboard.nextLine();
System.out.printf("尾端遞迴:%d\n", sumTail(s, 0));
System.out.printf("迴圈:%d\n", sumLoop(s, 0));
System.out.print("Input a string of numbers: ");
s = keyboard.nextLine();
System.out.printf("尾端遞迴:%d\n", sumTail(s, 0));
System.out.printf("迴圈:%d\n", sumLoop(s, 0));
}
static int sumTail(String s,int x){
if(s.equals("")){
return x;
}
else {
return sumTail(s.substring(1) , x+Integer.parseInt(s.substring(0,1)));
}
}
static int sumLoop(String s,int x){
while(!s.equals("")){
x+=Integer.parseInt(s.substring(0,1));
s=s.substring(1);
}
return x;
}
}
407 尾端遞迴計算總和
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言