Char Sum | Competitive Programming Questions with Answers in Java

Competitive Programming Questions with Answers in Java

Char Sum

Problem

Consider All lowercase Alphabets of the English language. Here we consider each alphabet from a to z to have a certain weight. The weight of the alphabet a is considered to be 1, b to be 2, c to be 3 and so on until z has a weight of 26. In short, the weight of the alphabet a is 1, and the weight of all other alphabets is the weight of its previous alphabet + 1.
Now, you have been given a String S consisting of lowercase English characters. You need to find the summation of weight of each character in this String.
For example, Consider the String aba
Here, the first character a has a weight of 1, the second character b has 2 and the third character a again has a weight of 1. So the summation here is equal to : 1+2+1=4

Input Format
The first and only line of input contains the String S.

Output Format
Print the required answer on a single line

Constraints
1≤|S|≤100
Sample Input
aba

Sample Output
4

Solution

import java.util.*;

class TestClass {
    public static void main(String args[] ) throws Exception {
        int a=0, i, l, sum=0;
        char ch;
        Scanner s = new Scanner(System.in);
        String str = s.nextLine();
        l = str.length();
        for(i=0; i<l; i++)
        {
            ch=str.charAt(i);
        switch(ch)
        {
        case 'a': a=1; break;
        case 'b': a=2; break;
        case 'c': a=3; break;
        case 'd': a=4; break;
        case 'e': a=5; break;
        case 'f': a=6; break;
        case 'g': a=7; break;
        case 'h': a=8; break;
        case 'i': a=9; break;
        case 'j': a=10; break;
        case 'k': a=11; break;
        case 'l': a=12; break;
        case 'm': a=13; break;
        case 'n': a=14; break;
        case 'o': a=15; break;
        case 'p': a=16; break;
        case 'q': a=17; break;
        case 'r': a=18; break;
        case 's': a=19; break;
        case 't': a=20; break;
        case 'u': a=21; break;
        case 'v': a=22; break;
        case 'w': a=23; break;
        case 'x': a=24; break;
        case 'y': a=25; break;
        case 'z': a=26; break;
        }
            sum=sum+a;
        }
        System.out.println(sum);
    }
}

Comments