简体   繁体   中英

How to calculate the sum of digits in a number iteratively - java/bluej

I am creating two methods - one that calculates the sum of the digits in a number recursively, and the other iteratively.

I have created the recursive method, and for the most part I understand the concept of finding the sum of digits, but I am not sure how to correctly put it into an iterative method. My code does not give me the correct output.

  public static int iterativeDigitSum(long n) {
        if(n < 0){ 
           String err = "n must be positive. n = " + n;
         throw new IllegalArgumentException(err);
       }
     if(n == 0){
           return 0;
       }

        long sum = 0;
        long i = 0;
     while(n > 0){
             i = n % 10;
             sum = sum + n;
             n = n / 10;
       }
       int inSum = (int)sum;
       return inSum;
}

The number "n" is 10, meaning the expected output is 1. I am getting 11. Could you please explain to me what I am doing wrong, and possibly how to fix it? Thank you so much.

Basically, the algorithm consists of three steps:

  1. Get the rightmost digit of the number. Since each digit in a number has a rank of units, tens, hundreds, thousands etc based on its position the rightmost digit is the remainder of dividing the number by 10:

    digit = n % 10

  2. Sum the digit up:

    sum += digit

  3. Move all the digits one place to the right by dividing the number by 10. The number becomes 10 times smaller:

    n = n / 10

    Effectively, this will "provide" the next rightmost digit for step 1.

The above three steps are repeated until the value of number becomes zero.

You can help yourself visualize the above explanation by adding some "debugging" information into your code:

public static int iterativeDigitSum(long n)
{
    long sum = 0;
    int i = 1;
    System.out.println("i\tn\tdigit\tsum");        
    while(n > 0) {
        long digit = n % 10;
        sum += digit;            
        System.out.println(i + "\t" + n + "\t" + digit + "\t" + sum);
        n = n / 10;
        i++;
    }
    System.out.println("\t" + n + "\t\t" + sum);
    return (int)sum;
}

Please note that the i variable is used to count the loop iterations and the digit variable holds the rightmost digit of the number in each iteration.

Given the number 10, the output to the BlueJ console is:

i   n     digit   sum
1   10    0       0
2   1     1       1
    0             1

and for the number 2019:

i   n       digit   sum
1   2019    9       9
2   201     1       10
3   20      0       10
4   2       2       12
    0               12

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM