-->

Add the numbers in string

Posted by Admin on
Given a string as input, add all the numbers that are part of the string. Note that one or more spaces ' ' demarcate two numbers. Also there is no negative number in the string. 
addNumbers("12 24 36")=72
addNumbers("12 12 100")=124



public class AddNumbers{
       static String testcase1 = "12 12 100";
      
       public static void main(String args[]){
              AddNumbers testInstance = new AddNumbers();
              int result = testInstance.addNumbers(testcase1);
              System.out.println("Result : "+result);
       }
      
       //function to add numbers in the string
       public int addNumbers(String str){
              str=remove(str);
              int len=str.length();
              int sum=0;
              String strNew="";
              for(int i=0;i<len;i++)
              {
                     char ch=str.charAt(i);
                     if(ch==' ')
                     {
                     int num=toNumber(strNew);
                     sum=sum+num;
                     strNew="";
                     }
                     else if(i==len-1)
                     {
                           strNew=strNew+ch;
                           int num=toNumber(strNew);
                           sum=sum+num;
                     }
                     else
                     {
                     strNew=strNew+ch;
                     }
                    
              }
              return sum;
       }
      
       //function to remove multiple spaces from the string
       public String remove(String sentence){
       int len=sentence.length();
       String strNew="";
       for(int i=0;i<len;i++)
       {
              char ch=sentence.charAt(i);
              if(ch!=' ')
              {
                     strNew=strNew+ch;
              }
              else if(ch==' ' && sentence.charAt(i-1)!=' ')
              {
                     strNew=strNew+ch;
              }
             
       }
       return strNew;
       }

       //function to convert string into number
       public int toNumber(String str){
              int num=0;
              int len=str.length();
              for(int i=0;i<len;i++)
              {
                     int digit=str.charAt(i)-'0';
                     num=num*10+digit;
              }
              return num;
       }
}

Please comment if you find any mistake.

No comments:

Post a Comment