Java > String-3 > sumNumbers (CodingBat Solution)

Problem:

Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (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.)

sumNumbers("abc123xyz") → 123
sumNumbers("aa11b33") → 44
sumNumbers("7 11") → 18


Solution:

public int sumNumbers(String str) {
  int len = str.length();
  int sum = 0;
  String tmp = "";
  
  for (int i = 0; i < len; i++) {
    if (Character.isDigit(str.charAt(i))) {
      if (i < len-1 && Character.isDigit(str.charAt(i+1))) {
        tmp += str.charAt(i);
      }
      else {
        tmp += str.charAt(i);
        sum += Integer.parseInt(tmp);
        tmp = "";
      }
        
    }
  }
  
  return sum;
}

4 comments:

  1. public int sumDigits(String str) {
    int sum = 0;
    for(int i = 0; i<str.length(); i++){
    if (Character.isDigit(str.charAt(i)))
    sum += Integer.parseInt(str.substring(i,i+1));
    }
    return sum;
    }

    ReplyDelete
  2. public int sumNumbers(String str) {
    str = str + " ";
    int count = 0;
    String temp = "";

    for (int i = 0; i < str.length(); i++) {
    if (Character.isDigit(str.charAt(i))) {
    temp += str.charAt(i);
    }
    else if (!(temp.isEmpty())) {
    count += Integer.parseInt(temp);
    temp = "";
    }
    }
    return count;
    }

    ReplyDelete
  3. public int sumNumbers(String str) {
    if(str.length()<1)return 0;
    int res=0;
    int tmp=0;
    for(int i=0; i<str.length(); i++) {
    if(Character.isDigit(str.charAt(i))) {
    tmp*=10;
    tmp+= Integer.parseInt(str.substring(i, i+1));
    }
    if(i==str.length()-1 || !Character.isDigit(str.charAt(i+1))) {
    res+=tmp;
    tmp=0;
    }
    }
    return res;
    }

    ReplyDelete
  4. public int sumNumbers(String str) {
    int sum=0, num=0;
    for (final char c : (str.concat(".")).toCharArray())
    if (Character.isDigit(c))
    num = num * 10 + (c - '0');
    else {
    sum += num;
    num = 0;
    }
    return sum;
    }

    ReplyDelete