Check if Word Equals Summation of Two Words

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 firstWordsecondWord, 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.

Example 1:

Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb"
Output: true
Explanation:
The numerical value of firstWord is "acb" -> "021" -> 21.
The numerical value of secondWord is "cba" -> "210" -> 210.
The numerical value of targetWord is "cdb" -> "231" -> 231.
We return true because 21 + 210 == 231.

Example 2:

Input: firstWord = "aaa", secondWord = "a", targetWord = "aab"
Output: false
Explanation: 
The numerical value of firstWord is "aaa" -> "000" -> 0.
The numerical value of secondWord is "a" -> "0" -> 0.
The numerical value of targetWord is "aab" -> "001" -> 1.
We return false because 0 + 0 != 1.

Approach

C++

#include <bits/stdc++.h>
using namespace std;

bool isSumEqual(string firstWord,
                string secondWordstring targetWord)
{
    string sum1 = ""sum2 = ""sum3 = "";

    for (int i = 0i < firstWord.size(); i++)
    {
        sum1 += to_string(firstWord[i] - 'a');
    }

    for (int i = 0i < secondWord.size(); i++)
    {
        sum2 += to_string(secondWord[i] - 'a');
    }

    for (int i = 0i < targetWord.size(); i++)
    {
        sum3 += to_string(targetWord[i] - 'a');
    }
    if (stoi(sum1) + stoi(sum2) == stoi(sum3))
        return true;
    return false;
}

int main()
{
    string firstWord = "acb";
    string secondWord = "cba"targetWord = "cdb";

    if (isSumEqual(firstWordsecondWordtargetWord))
        cout << "true\n";
    else
        cout << "false\n";

    return 0;
}


No comments:

Post a Comment