【题目】给定一个字符串str,求其中全部数字串代表的数字之和。

【题目】给定一个字符串str,求其中全部数字串代表的数字之和。

【要求】1.忽略小数点字符

​ 2.如果紧贴数字子串的左侧出现字符"-",当连续出现的数量为奇数时,则数字视为负,连续出现的数量为偶数时,则数字视为正。

public class NumSum {
	public static int numSum(String str) {
		if (str == null) {
			return 0;
		}
		int res = 0;
		int num = 0;
		int cur = 0;
		boolean isPos = true;
		char[] ch = str.toCharArray();
		for (int i = 0; i < ch.length; i++) {
			cur = ch[i] - '0';
			if (cur < 0 || cur > 9) {
				res += num;
				num = 0;
				if (ch[i] == '-') {
					if (i - 1 > -1 && ch[i - 1] == '-') {
						isPos = !isPos;
					} else {
						isPos = false;
					}
				} else {
					isPos = true;
				}
			} else {
				num = num * 10 + (isPos ? cur : -cur);
			}
		}
		res += num;
		return res;
	}
}

猜你喜欢

转载自blog.csdn.net/gkq_tt/article/details/86586779
今日推荐