无法理解代码的逻辑来找到均匀定位数字的总和

时间:2014-10-10 13:15:47

标签: java loops bluej

所以基本上问题是:

  

编写程序以接受来自用户的数字,并找到从左侧开始计数的均匀位数的总和。例如。如果输入为94852,则输出为9(4 + 5)。

现在,我知道这个问题可以通过将数字转换为字符串并使用数组来完成,但实际上还有更好的方法。

以下程序演示了方法 - :

public class Question {
    public static void main(int a) {
        int evenSum = 0, oddSum = 0;
        int b = a; //b is used as a's value eventually becomes 0.
        while(a>0) { 
           int sum = evenSum + a % 10; 
           evenSum = oddSum; //Switching sums(?)
           oddSum = sum; //Interestingly,oddSum stores the sum of the oddly positioed digits
           a = a / 10; 
        }   
        System.out.println("The number entered is "+b);
        System.out.println("The even sum is " + evenSum);
    }
}

当我在寻找替代解决方案时碰巧遇到了这个答案,这让我惊呆了。我根本无法理解逻辑。

有人可以解释这种方法的作用及其工作原理吗?

4 个答案:

答案 0 :(得分:0)

代码重复向右移位一位(整数除以10)。它通过模10(整数除法的余数)选择最右边的数字。

或者在循环中一步求和在一个和变量中,在另一个和变量的下一步中。

所以有两个总和:"奇数"和"甚至"位数。

然而,正如你所说," odd"和"甚至"对于来自 left 的位置,并且循环从开始,你不能说在第一步,第一个数字,那个数字处于奇数或偶数位置(从左边算起。)

因此你需要将奇数和偶数位置相加。

通过在每一步中交换奇数和偶数总和,确保始终将最后一位数字添加到oddSum,evenSum确实是"偶数"总和。

答案 1 :(得分:0)

代码有效,因为我们使用十进制数字系统,换句话说,数字中的每个位置都是右边一个位置的10倍。

a%10是除以10的余数,并且因为除了1位以外的所有位置的所有数字都可以被10整除,所以剩下的就是那些数字。

另一方面,

a = a/10正在对数字进行整数除法(除去其余部分),这意味着你将数字的一位数字删掉。

evenSumoddSum交替使用两个和,以便前一个循环itterations sum始终存储在偶数和这个迭代中,并以oddSum为单位。我们知道代码完成时的最后一次迭代将位于最左边的数字(问题定义中的第一个数字),因此将是奇数总和。

答案 2 :(得分:0)

Its a combination of maths & programming. I added a print statement after evenSum & this is the output what i got:

94852= a, 2 = a%10, 0 = evenSum,2 = sum in Step 1
9485= a, 5 = a%10, 2 = evenSum,5 = sum in Step 2
948= a, 8 = a%10, 5 = evenSum,10 = sum in Step 3
94= a, 4 = a%10, 10 = evenSum,9 = sum in Step 4
9= a, 9 = a%10, 9 = evenSum,19 = sum in Step 5
The number entered is 94852
The even sum is 9

2 rules are involved here:

1. Dividing a number by 10 leaves a decimal which gets omitted if variable declared as int.
2. Dividing a number by 10 leaves the remainder as the last digit if variable declared as int.

Rest all is self explanatory !  

答案 3 :(得分:0)

这是提取数字

的每个数字的基本代码
while (a > 0) {
   int digit = a % 10;
   a /= 10;
}

诀窍是将每个数字交替添加到偶数或奇数和

a = 0; b = 0; // these represent evenSum and oddSum
repeat
   take the last digit
   add the digit to b
   swap a and b // alternates
   remove the last digit

将数字添加到b是使用临时变量'sum'

完成的