题目
字符串中数字子串的求和
java代码
package com.lizhouwei.chapter5;
/**
* @Description: 字符串中数字子串的求和
* @Author: lizhouwei
* @CreateDate: 2018/4/23 21:05
* @Modify by:
* @ModifyDate:
*/
public class Chapter5_2 {
public int numSum(String str) {
char[] charArr = str.toCharArray();
int res = 0;
int num = 0;
int cur = 0;
boolean posi = true;
for (int i = 0; i < charArr.length; i++) {
cur = charArr[i] - '0';
if (cur < 0 || cur > 9) {
res += num;
num = 0;
if (charArr[i] == '-') {
if (i > 0 && charArr[i - 1] == '-') {
posi = !posi;
} else {
posi = false;
}
} else {
posi = true;
}
} else {
num = num * 10 + (posi ? cur : -cur);
}
}
res += num;
return res;
}
//测试
public static void main(String[] args) {
Chapter5_2 chapter = new Chapter5_2();
String str = "A--1CD---2EE33";
System.out.println("A--1CD---2EE33中数字之和:" + chapter.numSum(str));
}
}
结果
![1369004-20180423215154414-786172521.png](https://i-blog.csdnimg.cn/blog_migrate/ec0178d44a9dede193a269100e2338d2.png)