Score a word by letter positions
A word game scores each letter by its position in the alphabet: a is 1, b is 2, and so on up to z is 26.
- Each lowercase letter a-z adds its position (a=1, b=2, ..., z=26).
- Characters that are not lowercase letters are ignored.
- An empty string scores zero.
wordScore(word: string) → int
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
int wordScore(std::string word) {
}
Worked examples
| Call | Result |
|---|---|
wordScore(std::string("abc")) | 6 |
wordScore(std::string("hello")) | 52 |
wordScore(std::string("")) | 0 |
wordScore(std::string("a")) | 1 |
Hint
Subtract the character code of a from each letter to get its value.
Reference solution in C++
int wordScore(std::string word) {
int sum = 0;
for (char c : word) {
if (c >= 'a' && c <= 'z') sum += c - 'a' + 1;
}
return sum;
}