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

Summing digits of an alphanumeric string

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

Problem

I am going through the Java CodingBat exercises. Here is the one I have just completed:


Given a string, return the sum of the digits 0-9 that appear in the string, ignoring all other characters. Return 0 if there are no digits in the string.

Here is my code:

public int sumDigits(String str) {

    StringBuilder strAppend = new StringBuilder();

    for (int i = 0; i < str.length(); i++) {
        if (Character.isDigit(str.charAt(i))) {
            strAppend.append(str.charAt(i));
        }
    }

    int total = 0;
    String strDigits = strAppend.toString();

    for (int i = 0; i < strDigits.length(); i++) {
        total += Integer.parseInt(strDigits.substring(i, i+1));
    }

    return total;

}


My questions are:

  • Should I be using one for loop instead of two?



  • Is it correct to be converting to StringBuilder to avoid concatenating a string?



  • Is it right to convert from string to int towards the end of the method, or convert as the digits are found?

Solution

Your question is surprising in the sense that you use the somewhat obscure isDigit method (not many people are aware of that one), yet you do not use the similar Character.getNumericValue(...) method.

Using that method, you can remove the second loop (as you suspected). It also answers the second question - there is no need for a StringBuilder, or the int conversion:

int total = 0;
for (char c : str.toCharArray()) {
    if (Character.isDigit(c)) {
        total += Character.getNumericValue(c);
    }
}
return total;

Code Snippets

int total = 0;
for (char c : str.toCharArray()) {
    if (Character.isDigit(c)) {
        total += Character.getNumericValue(c);
    }
}
return total;

Context

StackExchange Code Review Q#86726, answer score: 11

Revisions (0)

No revisions yet.