HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Sum of an integer's digits

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
digitsintegersum

Problem

The question is that in a given integer n you have to sum its digits. For example, the sum for 111 would be 3.

Though I managed to solve the problem, I have a good feeling that this algorithm can still be improved.

public static int digit(int n){
    String numbers = n+"";
    int sum = 0;
    for(int x = 0; x < numbers.length(); x++){
        sum += Integer.parseInt(numbers.charAt(x)+"");
    }

    return sum;
}

Solution

There is an arithmetic solution to this problem, without converting to a string. It's probably what the string conversion does internally and will therefore likely be much more efficient.

Quoting Wikipedia:


The digit sum of a number \$x\$ in base \$b\$ is given by
$$
\sum_{n=0}^{\lfloor \log_b x\rfloor} \frac{1}{b^n}(x \bmod b^{n + 1} - x \bmod b^n).
$$

This StackOverflow answer has an implementation in C# (which is very similar to Java):

sum = 0;
while (n != 0) {
    sum += n % 10;
    n /= 10;
}


In addition, I'd like to comment on the naming of your method. In my opinion, digit doesn't describe its function very well. Instead I'd recommend something similar to digitSum.

Note that this approach doesn't handle negative numbers. They cause the function to go into an infinite loop. To handle that case, you can something like the following:

public static int digitSum(int n) {
    int sum = 0;
    bool isNegative = false;

    if (n < 0) {
        isNegative = true;
        n *= -1;
    }

    while (n != 0) {
        sum += n % 10;
        n /= 10;
    }

    if (isNegative) {
        return -sum;
    } else {
        return sum;
    }
}

Code Snippets

sum = 0;
while (n != 0) {
    sum += n % 10;
    n /= 10;
}
public static int digitSum(int n) {
    int sum = 0;
    bool isNegative = false;

    if (n < 0) {
        isNegative = true;
        n *= -1;
    }

    while (n != 0) {
        sum += n % 10;
        n /= 10;
    }

    if (isNegative) {
        return -sum;
    } else {
        return sum;
    }
}

Context

StackExchange Code Review Q#146216, answer score: 6

Revisions (0)

No revisions yet.