3 回答
TA贡献1802条经验 获得超5个赞
好吧,这是使用递归解决问题的一种简单方法。我使用正则表达式来获取数字,因为您没有表示不允许这样做。
public static int sum(String a) {
Matcher m = Pattern.compile("(\\d\\d+)").matcher(a);
if (m.find()) {
return Integer.parseInt(m.group(1)) + sum(a.substring(m.end()));
}
return 0;
}
TA贡献1844条经验 获得超8个赞
这就是我的处理方式:
public class AddMultipleDigitsInStringRecursive
{
public static void main(String[] args)
{
String input = "5a-f5-11";
System.out.println("Input: " + input);
int sum = sumDigits(input);
System.out.println("Sum: " + sum);
}
public static int sumDigits(String input)
{
return addDigits(input, 0, "");
}
private static int addDigits(String input, int index, String curNumber)
{
if(index < input.length())
{
int curSum = 0;
String curChar = input.substring(index, index + 1); // get the current character (as a String)
if (Character.isDigit(curChar.charAt(0))) // if it's a digit, append it to the current number
{
curNumber = curNumber + curChar;
}
else // it's not a digit, do we have a number pending?
{
if (!curNumber.isEmpty())
{
curSum = Integer.parseInt(curNumber); // convert current number to an Integer
}
curNumber = ""; // reset the current number so we can accumulate more digits when they are found
}
// return the sum of the current number (if any) with any other numbers that are found
return curSum + addDigits(input, index + 1, curNumber);
}
else // reached the end of the string; was there a number pending?
{
int curSum = 0;
if (!curNumber.isEmpty())
{
curSum = Integer.parseInt(curNumber);
}
return curSum;
}
}
}
TA贡献1816条经验 获得超6个赞
不知何故设法弄清楚了,它确实有效:
public static int sum(String str, int i, String subStr, int sum) {
if(str.length() <= i) return sum;
String newSubStr = subStr;
char oneStr = str.charAt(i);
if(!Character.isDigit(oneStr)) //if the new index is not a number and the index before IS a number>
{
if(isNumeric(subStr))// new index IS a number, therefore will sum up.
{
int num = Integer.parseInt(subStr);
sum+=num;
newSubStr = "";
}
}
else
{
String temp = oneStr+"";
newSubStr += temp;
}
System.out.println(sum);
return sum(str, i+1, newSubStr, sum);
}
添加回答
举报