Java 奇数位总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19640762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum of the odd-place digits
提问by Dan Gurewitch
I am trying to sum every other digit in the card number by doing this:
我试图通过这样做来对卡号中的所有其他数字求和:
/*
Return the sum of the odd-place digits.
*/
public static int sumOfoddPlace(long number)
{
int maxDigitLength = 16;
int sum = 0;
for (int i = 1; i <= maxDigitLength; i++)
{
if (i % 2 == 1)
{
sum = sum + (int)(number % 10);
}
break;
}
return sum;
}
All I get is 6. The sum I am looking for is supposed to be 37.
我得到的只是 6。我要找的总和应该是 37。
回答by Rohit Jain
You're breaking out of the loop on the very first iteration only. So, you won't go past to another iteration.
您仅在第一次迭代时就跳出了循环。因此,您不会再进行另一次迭代。
However, removing the break
too won't solve your problem. number % 10
will always give you the last digit of the number, and not every alternate number. You should follow this approach:
但是,删除break
太不能解决您的问题。number % 10
将始终为您提供号码的最后一位,而不是每个备用号码。您应该遵循以下方法:
num % 10
- Will give you last digit.- Then update the
num
by trimming off the last 2 digits. - Repeat
num % 10
- 会给你最后一位数字。- 然后
num
通过修剪最后 2 位数字来更新 。 - 重复
回答by user2909923
Try this ... this should work for you
试试这个……这应该适合你
public static int sumOfoddPlace(long number)
{
int maxDigitLength = 16;
int sum = 0;
for (int i = 0; i < maxDigitLength; i++)
{
if (i % 2 != 0)
{
sum = (sum + (int)(number % 10));
number = number/10;
}else {
number = number/10;
}
}
return sum;
}
What I have done here is if i
is odd, I take a mod of the number so I get the last digit of the number and then add it to sum and then I get rid of the last digit by dividing it with 10 and if the number is even I just get rid of the digit in the i
th position.
我在这里所做的是如果i
是奇数,我取一个数字的模,所以我得到数字的最后一位数字,然后将其添加到总和,然后我通过将其除以 10 来摆脱最后一位数字,如果数字甚至我只是摆脱了i
第 th 位的数字。
Here I am collecting the digits in odd places in reverse order.
在这里,我以相反的顺序收集奇数位置的数字。
回答by Rushabh Shah
Here is updated code in which i have removed logic of flag.This is shorter and easier to understand.
这是我删除了标志逻辑的更新代码。这更短也更容易理解。
public static int sumOfOddDigits(long number){
int sum = 0;
String newString = new StringBuilder(String.valueOf(number)).reverse().toString();
number = Long.parseLong(newString);
while (number != 0){
sum = (int) (sum + number % 10);
number = number / 100;
}
return sum;
}
回答by Hans Z
I haven't seen the minimum solution yet, so here goes:
我还没有看到最小的解决方案,所以这里是:
public static int sumOddDigits(long input) {
int sum = 0;
for (long temp = input; temp > 0; temp /= 100) {
sum += temp % 10;
}
return sum;
}
You don't need to divide by 10 and check if it's an even number, you can just divide by 100 every time.
你不需要除以 10 并检查它是否是偶数,你可以每次除以 100。
Demo: http://ideone.com/sDZfpU