Learn-dsa..in 30 days!



























CC-4 : Sum of letters.

Description:

Given input String str with lowercase characters, find the integer equivalent of each character and find sum of all characters in str after conversion to integers as mentioned above.

Test cases and expected outputs:

Input Parameters Expected outputs
str1="hello"; 52
str1="boy"; 42
str1="java"; 34

Pseudocode:

The java method should accept following input parameters: str (String).
Extract the characters from str into char array names chars.
Declare an integer variable alphaSum, we will use this to store sum of letters converted into integers.
Iterate through chars using for loop using idx as loop variable, starting from index 0 and incrementing idx till we reach chars.length-1:
For each character in chars, convert character to integer using this code: ((str.charAt(idx)-'a')+1.
Increment alphaSum with above integer in each iteration.
When above loop completes, alphaSum contains the sum of characters converted to integers, so return alphaSum.

Code:

public int stringAlphabetSum(String str) {
	char[] chars=str.toCharArray();
	int alphaSum=0;
	for (int idx=0;idx < chars.length;idx++) {
		alphaSum += ((str.charAt(idx)-'a')+1);
	}
	return alphaSum;
}

Click here to download and run code and test cases !