我正在尝试解决 Project Euler #16:
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
问题看起来很简单,但我没有使用模数 10 而是尝试解决这样的问题:
public class Main {
public static void main(String[] args) {
long number = (long) Math.pow(2,100);
long sum=0;
String number2 = String.valueOf(number);
char[] digits = number2.toCharArray();
for (char digit : digits) {
sum = sum + digit;
}
System.out.println(sum);
}
}
但是它给出了错误的答案,我看不到我的错误,难道不能用这种方式解决这个问题吗?
最佳答案
long
无法容纳该数字。您必须使用可以的数据类型重写。
参见Large Numbers in Java供指点。
关于java - 如何求一个数的各个数字之和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41406742/