[英]Issue while compare and sum digits of two numbers
So, the thing is that I have two lines with two numbers on each line.所以,问题是我有两行,每行有两个数字。 On each line the numbers are separated by space.
在每一行上,数字由空格分隔。 What I'm trying to do is to compare which number is bigger on the line and sum digits of the bigger number.
我想做的是比较线上哪个数字更大,并对更大数字的数字求和。
Example例子
1000 2000
2000 1000
In this case the output should be在这种情况下,output 应该是
2
2
because on the first line the right numbers is bigger and the sum of it digits is 2. The second line is the opposite.因为在第一行右边的数字更大,它的数字之和是 2。第二行是相反的。
What I have so far is this到目前为止我所拥有的是这个
int sum = 0;
for (int i = 0; i <= 2; i++) {
String numbers = scanner.nextLine();
String[] parts = numbers.split(" ");
double leftNumber = Double.parseDouble(parts[0]);
double rightNumber = Double.parseDouble(parts[1]);
if ( leftNumber > rightNumber ) {
while (leftNumber > 0) {
sum = (int) (sum + leftNumber % 10);
leftNumber = leftNumber / 10;
}
} else {
while (rightNumber > 0) {
sum = (int) (sum + rightNumber % 10);
rightNumber = rightNumber / 10;
}
}
System.out.println(sum);
}
Result that I've get is我得到的结果是
2
4
it is adding the second line result to the first one.它将第二行结果添加到第一行。 How can I avoid this?
我怎样才能避免这种情况?
Why not make things easier on yourself and just treat the integers as strings for the purpose of summing the digits?为什么不让事情变得更简单,而只是将整数视为字符串以求和数字呢?
while (scanner.hasNext()) {
int larger = Math.max(scanner.nextInt(), scanner.nextInt());
String sLarger = String.valueOf(larger);
int digitsSum = 0;
for (int i = 0; i < sLarger.length(); i++) {
digitsSum += sLarger.charAt(i) - '0';
}
System.out.printf("Larger number %s sums to %d%n", sLarger, digitsSum);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.