Sunday, December 15, 2013

Programming Challenges Question 2

Programming Challenges Question 
Write a program which will accept a single pair of strings separated by a comma; the program should calculate the sum of ascii values of the characters of each string. The program should then subtract the sum of the ascii values of the second string from the sum of the ascii values of the first string.

Suppose the following input is given to the program: 

123ABC,456DEF

Then the sum of the ascii values of the characters in '123ABC' is 348 and in '456DEF' it is 366. The Difference between these numbers is 348 – 366 = -18
The corresponding output to be printed by the program is: 
-18

/*****************************Code in JAVA********************************/
import java.io.*;
public class Main {
public static void main(String[] args) {
 
    try
    {

    InputStreamReader sr= new InputStreamReader(System.in);
    BufferedReader br= new BufferedReader(sr) ;
    String str=br.readLine();
    String data[]= str.split(",");
    int sum[]= new int[data.length];
    for(int i=0;i<data.length;i++)
    {
        for(int j=0;j<data[i].length();j++)
        {
           sum[i]=sum[i]+ (int) data[i].charAt(j);
        }
     
    }
    int dif=sum[0];
    for(int i=1;i<sum.length;i++)
        {
             dif=dif-sum[i];
         }
    System.out.println("Diff :"+dif);
    }
    catch(Exception ex)
    {
        System.out.println(ex);
    }
  }
}



No comments:

Post a Comment