给定一个字符串str,求其中全部整数数字之和
程序员文章站
2024-01-25 22:24:10
...
参考 https://blog.csdn.net/duoduo18up/article/details/82193122
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
Stack stack=new Stack();
int result=0;
for(int i=0;i<line.length();i++){
String temp=line.charAt(i)+"";
if(temp.matches("-")){
stack.push('-');
}
else if(temp.matches("\\d")){ //如果是数字
int count=0;
while(!stack.empty()){ //先弹出所有的符号
stack.pop();
count++;
}
stack.push(temp);
for(int j=i+1;j<line.length();j++){
String other=line.charAt(j)+"";
if(other.matches("\\d")) {
stack.push(other);
i=j;
}
else break;
}
int jinwei=1;
int result_temp=0;
while(!stack.empty()){
int number=Integer.valueOf((String)stack.pop());
result_temp=result_temp+number*jinwei;
jinwei=jinwei*10;
}
if(count%2!=0) result_temp=-result_temp;
result=result+result_temp;
}
}
System.out.println(result);
}