【题目】给定一个字符串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;
	}
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,以下是字符串数字字符个数的函数以及示例代码: ```python def count_digits(s): count = 0 for char in s: if char.isdigit(): count += 1 return count # 主函数示例 s = input("请输入字符串:") num_digits = count_digits(s) print("数字字符的个数为:", num_digits) ``` 在这个函数中,我们首先定义了一个变量 `count` 来统计数字字符的个数,然后遍历输入的字符串 `s` 中的每个字符,如果这个字符是数字字符,那么就把 `count` 的值加一。最后返回 `count` 的值即为字符串数字字符的个数。 在主函数中,我们首先通过 `input` 函数来获取用户输入的字符串,并将其传递给 `count_digits` 函数来计算数字字符的个数。最后将统计出来的数字字符个数打印输出即可。 ### 回答2: 题目编写一个函数来统计给定字符串数字字符的个数,并且在主函数中输入字符串并输出统计的结果。因此,我们需要先定义一个函数来实现统计数字字符的功能。 函数定义: ``` int countDigitChar(char str[]) { int count = 0; int i; for (i = 0; str[i] != '\0'; i++) { if (isdigit(str[i])) { count++; } } return count; } ``` 这个函数的功能很简单,就是遍历字符串中的每一个字符,如果这个字符是数字字符,就将计数器加一,最后返回计数器的值。其中,isdigit() 是一个 C 库函数,用于判断一个字符是否为数字字符。 接下来,我们可以在主函数中调用这个函数来统计字符串数字字符的个数: ``` #include <stdio.h> #include <ctype.h> int countDigitChar(char str[]); int main() { char str[100]; int count; printf("请输入一个字符串:"); scanf("%s", str); count = countDigitChar(str); printf("字符串数字字符的个数为:%d\n", count); return 0; } int countDigitChar(char str[]) { int count = 0; int i; for (i = 0; str[i] != '\0'; i++) { if (isdigit(str[i])) { count++; } } return count; } ``` 上面的代码中,首先定义了一个字符串数组 str 和一个整型变量 count,用于存储输入的字符串和计算得到的数字字符个数。然后提示用户输入字符串,并通过 scanf() 函数将输入的字符串存储到 str 数组中,然后调用 countDigitChar() 函数计算数字字符的个数,并将计算结果存储到 count 变量中。最后输出计算结果。 总的来说,这个问题的解决方法比较简单,只需要编写一个遍历字符串的函数,然后在主函数中调用即可。 ### 回答3: 这是一个比较简单的函数,直接遍历字符串,判断每个字符是否是数字字符,如果是则累加计数器。 下面是代码实现: ```python def count_digits(s): count = 0 for c in s: if c.isdigit(): count += 1 return count # 主函数 if __name__ == '__main__': s = input("请输入一个字符串:") count = count_digits(s) print("数字字符个数为:", count) ``` 首先定义了一个 `count_digits` 函数,它接收一个字符串作为参数,返回数字字符的个数。 主函数中,先输入一个字符串,然后调用 `count_digits` 函数,得到数字字符的个数,最后输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值