我想使用遞歸將String輸入轉換爲int。這是我想出的代碼,但如果我的輸入是123456,它只返回124.如果我輸入1234567,它會給出錯誤。如何使用遞歸將字符串轉換爲int
import java.util.*;
public class Problem1 {
static int x =0;
static int counter = 0;
//input
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String s= scan.nextLine();
System.out.println(recursive(s));
}
//recursive method
public static int recursive(String s){
if(s.length()==1){
x=(x*10)+ Integer.parseInt(s.substring(0,1));
return x;
}
else{
x = (x*10)+Integer.parseInt(s.substring(0,1));
counter++;
return recursive(s.substring(counter,s.length()-1));
}
}
}
您的o/p期望值是多少?爲什麼你乘以10? – user1428716