Problem:
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. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an int.)
sumDigits("aa1bc2d3") → 6
sumDigits("aa11b33") → 8
sumDigits("Chocolate") → 0
Solution:
public int sumDigits(String str) { int len = str.length(); int sum = 0; for (int i = 0; i < len; i++) { if (Character.isDigit(str.charAt(i))) { String tmp = str.substring(i,i+1); sum += Integer.parseInt(tmp); } } return sum; }
public int sumDigits(String str) {
ReplyDeleteint result = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
result += Integer.parseInt(String.valueOf(str.charAt(i)));
}
}
return result;
}
Recursively:
ReplyDeletepublic int sumDigits(String str) {
if(str.length() == 0) return 0;
if(Character.isDigit(str.charAt(0)))
return Character.getNumericValue(str.charAt(0)) + sumDigits(str.substring(1));
return sumDigits(str.substring(1));
}
public int sumDigits(String str) {
ReplyDeleteint sum =0;
for(final char c : str.toCharArray()){
if (Character.isDigit(c)){
sum += Character.getNumericValue(c);
}
}
return sum;
}
public int sumDigits(String str) {
ReplyDeleteint res = 0;
for(int i = 0; i < str.length(); i++){
if(Character.isDigit(str.charAt(i))){
res += Integer.parseInt(str.charAt(i)+"");
}
}
return res;
}