Problem Statement:
You are given 3 words. You need to check if the summation of the letters lead up to third word.
Example
Input: s1 = "acb", s2 = "cba", s3 = "cdb" Output: true s1 = "acb" -> 0 2 1 s2 = "cba" -> 2 1 0 s3 = "cdb" -> 2 3 1 s1 + s2 = s3 21 + 210 = 231
Solution
The solution is very simple.
Note that, we should not take the ascii value, but to take the position of the alphabets.
a -> 0
b -> 1
…
z -> 25
So, what we do is, we will subtract the ‘a’ value with the given letter. We will get the required position.
Example:
For acb,
a – a = 0
c – a = 2
b – a = 1
Solution in C++
#include <algorithm> //visit www.ProDeveloperTutorial.com for 450+ solved questions #include <iostream> #include <string> #include <stack> #include <vector> #include <unordered_map> #include <queue> using namespace std; bool is_sum_equal(string firstWord, string secondWord, string targetWord) { int first=0,second=0,target=0; for(int i=0;i<firstWord.size();i++) first = first*10 + (firstWord[i]-'a'); for(int i=0;i<secondWord.size();i++) second = second*10 +(secondWord[i]-'a'); for(int i=0;i<targetWord.size();i++) target = target*10 +(targetWord[i]-'a'); return first+second == target; } int main() { string s1 = "acb"; string s2 = "cba"; string s3 = "cdb"; if(is_sum_equal(s1, s2, s3)){ cout<<"Sum are equal"<<endl; } else { cout<<"Sum are not equal"<<endl; } return 0; }
Output:
Sum are equal