【发布时间】:2021-02-15 11:54:24
【问题描述】:
这是我们老师给我们的代码,当我问为什么我们从 arr[i] 中减去“0”时,她只是说它用于排除任何不是数字的东西。谁能解释一下它是如何工作的?
//program to print the sum of all the digits in a string
//
import java.io.IOException;
class CSumOfDigit
{
public static void main(String[] args) throws IOException {
String str="67281";
char arr[]=str.toCharArray();
long sum=0;
for(int i=0;i<arr.length; i++){
sum=sum+(arr[i]-'0');
}
System.out.println("Sum of digits is:"+sum);
}
}
【问题讨论】:
-
获得与
int sum = str.chars().sum() - '0' * str.length();相同结果的详细方法