题目
给定一个字符串str,求其中全部数字串所代表的数字之和。
要求:
- 忽略小数点字符。
- 如果紧贴数字子串的左侧出现字符“-”,当连续出现的数量为奇数时,数字视为负;连续出现的数量为偶数时,数字视为正。
代码实现
public int numSum(String str) {
if (str == null) {
return 0;
}
int res = 0;
int num = 0;
boolean posi = true;
int cur = 0;
for (int i = 0; i < str.length(); i++) {
cur = str.charAt(i) - '0';
if (cur < 0 || cur > 9) {
res += num;
num = 0;
if (str.charAt(i) == '-') {
if (i > 0 && str.charAt(i - 1) == '-') {
posi = !posi;
} else {
posi = false;
}
} else {
posi = true;
}
} else {
num = num * 10 + (posi ? cur : -cur);
}
}
res += num;
return res;
}