题目描述
输入字符串s,输出s中包含所有整数的最小和。
说明:
字符串s,只包含 a-z A-Z ±
合法的整数包括
1)正整数:一个或者多个0-9组成,如 0 2 3 002 102
2)负整数:负号 – 开头,数字部分由一个或者多个0-9组成,如 -0 -012 -23 -00023
输入描述
包含数字的字符串
输出描述
所有整数的最小和
用例1
输入
bb1234aa
输出
10
用例2
输入
bb12-34aa
输出
-31
说明
1+2+(-34) = -31
import java.util.Scanner;
import java.math.BigInteger;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
boolean tag = false;
StringBuilder builder = new StringBuilder();
BigInteger result = new BigInteger("0");
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){
if(!tag){
result = result.add(new BigInteger(str.charAt(i) + ""));
}else{
builder.append(str.charAt(i));
}
}else{
if(builder.length() > 0){
result = result.subtract(new BigInteger(builder.toString()));
builder = new StringBuilder();
}
if(str.charAt(i) == '-'){
tag = true;
}
}
}
if(builder.length() > 0){
result = result.subtract(new BigInteger(builder.toString()));
}
System.out.println(result);
}
}
1352

被折叠的 条评论
为什么被折叠?



