Java > String-3 > sumDigits (CodingBat Solution)

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;
}

4 comments:

  1. public int sumDigits(String str) {
    int 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;
    }

    ReplyDelete
  2. Recursively:

    public 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));
    }

    ReplyDelete
  3. public int sumDigits(String str) {
    int sum =0;
    for(final char c : str.toCharArray()){
    if (Character.isDigit(c)){
    sum += Character.getNumericValue(c);
    }
    }
    return sum;
    }

    ReplyDelete
  4. public int sumDigits(String str) {
    int res = 0;
    for(int i = 0; i < str.length(); i++){
    if(Character.isDigit(str.charAt(i))){
    res += Integer.parseInt(str.charAt(i)+"");
    }
    }
    return res;
    }

    ReplyDelete