Monday 5 January 2015

Find the sum of all the numbers present in a String?

Advertisement

This is a interview question can be asked in an experienced or fresher's interview to write a program which will add up all the integer value present in a string and print the added number.

Tips to think how to do it...

1. For this kind of problem always think of first matching the number in a String .
2. How you are going to match?
3. The only simplest way is with the help of ASCII of 0-9 .

Steps to do :

1. Take a int variable c=0.
2. Run the loop from 0 to String length.
3. Get the each index value using charAt() method which will return the char value.
4. Convert that char into int by typecasting or any other way.
5. Now check that ASCII fall into the range of 48-57 for 0-9 int number.
6. If it matches then first convert that number into integer using Integer.parseInt().
7. Then add with the c and store to the same variable i.e c.
8. Repeat from 3-7 till the end of the loop.
9. At the end of loop , Print c outside the loop.

Program


public class Lab1 {

public static void main(String[] args) {

String s="s16u7ty9";
int c=0;
for(int i=0;i<s.length();i++){
char ch=s.charAt(i); // Getting each char from String
int x=(int)ch;
for(int y=48;y<=57;y++){ // Loop for checking the ASCII
if(x==y){
int num=Integer.parseInt(""+ch); //Getting the int value
c=c+num;
}
}
}
System.out.println("Total Sum:"+c); // Final sum

}

}







EmoticonEmoticon