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 thestring
, ignoring all other characters. Return 0 if there are no digits in thestring
.
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 astring
? - Is it right to convert from
string
toint
towards the end of the method, or convert as the digits are found?