Check if Word Equals Summation of Two Words
Problem
The letter value of a character is its position in the alphabet, 0-indexed ('a'=0 … 'j'=9). The numerical value of a word made of letters 'a'..'j' is the number formed by concatenating its letter values, read as a base-10 number. Given firstWord, secondWord, and targetWord, return true if value(firstWord) + value(secondWord) == value(targetWord).
first = "acb", second = "cba", target = "cdb"truedef is_sum_equal(first_word, second_word, target_word):
def value(w):
v = 0
for ch in w:
v = v * 10 + (ord(ch) - ord("a"))
return v
return value(first_word) + value(second_word) == value(target_word)
function isSumEqual(firstWord, secondWord, targetWord) {
function value(w) {
let v = 0;
for (const ch of w) {
v = v * 10 + (ch.charCodeAt(0) - 97);
}
return v;
}
return value(firstWord) + value(secondWord) === value(targetWord);
}
class Solution {
private int value(String w) {
int v = 0;
for (char ch : w.toCharArray())
v = v * 10 + (ch - 'a');
return v;
}
public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
return value(firstWord) + value(secondWord) == value(targetWord);
}
}
int value(string w) {
int v = 0;
for (char ch : w)
v = v * 10 + (ch - 'a');
return v;
}
bool isSumEqual(string firstWord, string secondWord, string targetWord) {
return value(firstWord) + value(secondWord) == value(targetWord);
}
Explanation
Each letter 'a'..'j' stands for a digit 0..9 via ord(ch) - ord('a'). A whole word is then just those digits written side by side as an ordinary base-10 number.
The clean way to turn a digit sequence into its number is Horner's method: start at 0 and for each character do v = v * 10 + digit. After the last character, v holds the full value, and any leading-zero letters are absorbed naturally because multiplying 0 by 10 stays 0.
We apply this value helper to all three words, then check the single arithmetic condition value(first) + value(second) == value(target).
That is the entire problem — there are no edge cases beyond empty handling, and since word lengths are tiny the numbers fit comfortably in a 32-bit integer.
Example: first="acb" → digits 0,2,1 → 21. second="cba" → 2,1,0 → 210. target="cdb" → 2,3,1 → 231. Then 21 + 210 = 231 = 231, so the answer is true.