java语言 使用递归调用算法把串s中第一个出现的数字的值返回。如果找不到数字,返回-1
例如:
s = "abc24us43"  则返回2
s = "82445adb5"  则返回8
s = "ab"   则返回-1   

解决方案 »

  1.   

    需要递归吗?public static int getFirstNum(String s) {
        if (s == null) return -1;
        for (char c : s.toCharArray()) {
            if (c>='0' && c<='9') return (int)(c-'0');
        }
        return -1;
    }
    //调用
    String s = "abc24us43";
    int n = getFirstNum(s);//递归
    public static int getFirstNum(String s, int index) {
        if (s==null) return -1;
        if (index == s.length) return -1; //递归结束条件
        char c = s.charAt(index);
        if (c>='0' && c<='9') return (int)(c-'0');
        return (s, index+1);
    }
    //调用
    String s = "abc24us43";
    int n = getFirstNum(s, 0);
      

  2.   

    my god,笔误这么多
    public static int getFirstNum(String s, int index) {
        if (s==null) return -1;
        if (index == s.length()) return -1; //忘了length的括号了
        char c = s.charAt(index);
        if (c>='0' && c<='9') return (int)(c-'0');
        return getFirstNum(s, index+1); //忘了写函数名
    }
      

  3.   

    public class CSDNTest {
    public static String getNum(String str){
    for(int i=0;i<str.length()-1;i++){
    char  ch = str.charAt(i);
    try {
    int j = Integer.parseInt(ch+"");
    return j+"";
    } catch (NumberFormatException e) {

    }
    }
    return "-1";
    }
    public static void main(String[] args) {
    System.out.println(CSDNTest.getNum("abd3c"));
    }
    }
      

  4.   

    早上我已经自己写出来了
    public static int getFirstNum(String str){

    if(str==null||str.length()==0)  return -1;;
    char c=str.charAt(0);
    if(c>='0'&&c<='9') return c-'0';
    else return getFirstNum(str.substring(str.indexOf(c)+1));

    }