links: Algorithms MOC


Problem

The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.).

The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer.

  • For example, if s = "acb", we concatenate each letter’s letter value, resulting in "021". After converting it, we get 21.

You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive.

Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.

Solution

It’s a easy problem, we just have to loop through each character in string and convert it to the form of 0, 1 and so on. Once that’s done just check if first + second = target

/**
 * @param {string} firstWord
 * @param {string} secondWord
 * @param {string} targetWord
 * @return {boolean}
 */
var isSumEqual = function(firstWord, secondWord, targetWord) {
    let firstWordVal = Number([...firstWord].map(elem => letterToNumber(elem)).join(''))
    let secondWordVal = Number([...secondWord].map(elem => letterToNumber(elem)).join(''))
    let targetWordVal = Number([...targetWord].map(elem => letterToNumber(elem)).join(''))
    return firstWordVal + secondWordVal === targetWordVal
};
 
function letterToNumber(letter) {
    // 'a'.charCodeAt() -> 97 so when you pass 'a' it returns 0 and 'b' 1 and so on
    return letter.charCodeAt() - 97
}

tags: string

source: