Social Icons

Monday, May 3, 2010

sumDigits: Solutions for Javabat:16

Following question belongs to Strings3 category in Javabat.

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


Given hint almost solves the problem. We iterate through the String using a loop and check whether it is a digit by passing it to isDigit method . If it is a character we convert it to a String by adding an empty string , parse it as an int and finally add to the total. total will be returned. We are assured that the method won’t be passed minus values or floating point numbers , simplifies the matter.

public int sumDigits(String str) {
  int sum=0;
  for(int i=0; i<str.length(); i++){
       sum+= Integer.parseInt(str.charAt(i)+"");
  return sum;


Blogger Templates