Find the sum of alphabetical order of characters in a string
Last Updated :
14 Mar, 2023
Given string S of size N, the task is to find the sum of the alphabet value of each character in the given string.
Examples:
Input: S = “geek”
Output: 28
Explanation:
The value obtained by the sum order of alphabets is 7 + 5 + 5 + 11 = 28.
Input: S = “GeeksforGeeks”
Output: 133
Approach:
- Traverse all the characters present in the given string S.
- For each lowercase character, add the value (S[i] – ‘a’ + 1) to the final answer, or if it is an uppercase character, add (S[i] – ‘A’ + 1) to the final answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findTheSum(string alpha)
{
int score = 0;
for ( int i = 0; i < alpha.length(); i++)
{
if (alpha[i] >= 'A' && alpha[i] <= 'Z' )
score += alpha[i] - 'A' + 1;
else
score += alpha[i] - 'a' + 1;
}
return score;
}
int main()
{
string S = "GeeksforGeeks" ;
cout << findTheSum(S);
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static int findTheSum(String alpha)
{
int score = 0 ;
for ( int i = 0 ; i < alpha.length(); i++)
{
if (alpha.charAt(i) >= 'A' && alpha.charAt(i) <= 'Z' )
score += alpha.charAt(i) - 'A' + 1 ;
else
score += alpha.charAt(i) - 'a' + 1 ;
}
return score;
}
public static void main(String args[])
{
String S = "GeeksforGeeks" ;
System.out.println(findTheSum(S));
}
}
|
Python3
def findTheSum(alpha):
score = 0
for i in range ( 0 , len (alpha)):
if ( ord (alpha[i]) > = ord ( 'A' ) and ord (alpha[i]) < = ord ( 'Z' )):
score + = ord (alpha[i]) - ord ( 'A' ) + 1
else :
score + = ord (alpha[i]) - ord ( 'a' ) + 1
return score
if __name__ = = "__main__" :
S = "GeeksforGeeks"
print (findTheSum(S))
|
C#
using System;
class GFG
{
static int findTheSum( string alpha)
{
int score = 0;
for ( int i = 0; i < alpha.Length; i++)
{
if (alpha[i] >= 'A' && alpha[i] <= 'Z' )
score += alpha[i] - 'A' + 1;
else
score += alpha[i] - 'a' + 1;
}
return score;
}
public static void Main()
{
string S = "GeeksforGeeks" ;
Console.Write(findTheSum(S));
}
}
|
Javascript
<script>
function findTheSum(alpha)
{
let score = 0;
for (let i = 0; i < alpha.length; i++)
{
if (alpha[i].charCodeAt(0) >= 'A' .charCodeAt(0) && alpha[i].charCodeAt(0) <= 'Z' .charCodeAt(0))
score += alpha[i].charCodeAt(0) - 'A' .charCodeAt(0) + 1;
else
score += alpha[i].charCodeAt(0) - 'a' .charCodeAt(0) + 1;
}
return score;
}
let S = "GeeksforGeeks" ;
document.write(findTheSum(S));
</script>
|
Time Complexity: O(n)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...