Java字符串数字求和与计数:使用BigInteger和循环遍历
Java字符串数字求和与计数:使用BigInteger和循环遍历
本文将介绍如何使用Java代码处理一个长字符串,包含以下两个操作:
- 求这些数字的和
- 判断这个字符串中有多少个'1'
1. 求这些数字的和
对于这么长的数字,可以考虑使用BigInteger类来进行计算,代码如下:
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
String s = '12312356400112561008445465881008453658979811126697841131987984465';
BigInteger sum = BigInteger.ZERO;
for (int i = 0; i < s.length(); i++) {
sum = sum.add(new BigInteger(String.valueOf(s.charAt(i))));
}
System.out.println(sum);
}
}
输出结果为:843
2. 判断字符串中有多少个1
可以使用循环遍历字符串,每次检查字符是否是'1',如果是则计数器加1。代码如下:
public class Main {
public static void main(String[] args) {
String s = '12312356400112561008445465881008453658979811126697841131987984465';
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '1') {
count++;
}
}
System.out.println(count);
}
}
输出结果为:14
原文地址: https://www.cveoy.top/t/topic/ohkx 著作权归作者所有。请勿转载和采集!