[英]How to find sum of separate digits of a number?
I'm trying to solve Project Euler #16: 我正在尝试解决Euler项目#16:
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
2 ^ 15 = 32768,其位数之和为3 + 2 + 7 + 6 + 8 = 26。
What is the sum of the digits of the number 2^1000?
2 ^ 1000的数字总和是多少?
question looks simple but Instead of using modulus 10 I tried to solve the question like this: 这个问题看起来很简单,但是我没有使用模数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);
}
}
However it gives a wrong answer, I can't see my mistake, Isn't it possible to solve this question with this way? 但是,它给出了错误的答案,我看不到我的错误,这样是否可以解决这个问题?
A long
cannot hold the number. long
无法容纳该数字。 You must rewrite using a datatype that can. 您必须使用可以的数据类型进行重写。
See Large Numbers in Java for pointers. 有关指针,请参见Java中的大数 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.