Breaking

Friday, 5 May 2017

Embedded Three Digit Numbers Sum in java

Embedded Three Digit Numbers Sum

A string S is passed as the input with numbers embedded in it. The program must print the sum of all three digit numbers embedded in the string. The program must print 0 (zero) if no three digit numbers are embedded in the string.

Input Format:
The first line will contain the string S.

Boundary Conditions:
Length of S is from 2 to 200

Output Format:
The sum of all three digit numbers embedded in the string.

Example Input/Output 1:

     Input:
                teamscored307runsin50oversinthe3rdmatch
    Output:
                307
   Explanation:
                307 is the only three digit number embedded. Hence the sum is also 307.

Example Input/Output 2:
Input:
ibought234chocolates45icecreams121sticks600combsand9545mouse

Output:
955

Explanation:
The three digit numbers embedded in the string are 234, 121 and 600. Hence sum is 955.(9545 is a four digit number and hence not considered).

 Example Input/Output 3: 
Input:
monkey70parrot40okay
Output:
0
Explanation:No three digit numbers embedded in the string


CODE:

import java.util.*;
import java.util.Scanner;
import java.util.Arrays;
import java.lang.*;
import java.lang.Number;
import java.lang.Integer;
import java.io.*;


class yogesh
{
public static void main (String[] args) throws java.lang.Exception
{
   Scanner sc=new Scanner(System.in);
       String str=sc.next();
            int i=0,no,sum=0;
      String[] arr=str.split("[a-zA-Z]"); 
     // String[] arr=str.split(""); 
       int[] num=new int[100];
        for(String y:arr)
        {
            try
                 { 
                   no= Integer.parseInt(y);
                     }
                 catch(Exception ex) 
                 {
                     no=0; 
                 }
            if(no>99&&no<1000)
               sum+=no;
        }
      System.out.println(sum);
}

}


For more: keep on Following!!

No comments:

Post a Comment

Like