日期:2014-05-19  浏览次数:20742 次

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

------解决方案--------------------
需要递归吗?
Java code

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);

------解决方案--------------------
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"));
}
}