字符串中数字子串的求和
程序员文章站
2024-02-27 14:53:27
...
/**
* Created by lxw, [email protected] on 2017/10/31.
* 字符串中数字子串的求和
*/
public class StringNumSum {
public static void main(String[] args){
String str1 = "A1CD2E33";
String str2 = "A-1B--2C--D6E";
System.out.println(NumSum(str1));
System.out.println(NumSum(str2));
System.out.println();
}
public static int NumSum(String str){
if(str == null){
return 0;
}
char[] charArr = str.toCharArray();
int res =0;
int num = 0;
boolean posi = true;
int cur = 0;
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 - 1 > -1 && charArr[i - 1] == '-'){
posi = !posi;
}else {
posi = false;
}
} else {
posi = true;
}
} else {
num = num * 10 + (posi ? cur : -cur);
}
}
res += num;
return res;
}
}
上一篇: 从N个数中等概率打印M个数
下一篇: 老生常谈Python进阶之装饰器