LeetCode - Check if Word Equals Summation of Two Words Solution - The Coding Shala

Home >> LeetCode >> Check if Word Equals Summation of Two Words

 In this post, we will learn how to solve LeetCode's Check if Word Equals Summation of Two Words problem and will implement its solution in Java.

Check if Word Equals Summation of Two Words 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.

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.

Practice this problem on LeetCode.

LeetCode - Check if Word Equals Summation of Two Words Java Solution

Approach 1

Find the numerical value of the first and second string then compare the sum of both with the target's numerical value

Java Program: 

class Solution {
    public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
        int firstV = findValue(firstWord);
        int secondV = findValue(secondWord);
        int targetV = findValue(targetWord);
        return (firstV + secondV) == targetV;
    }
    
    int findValue(String str) {
        int res = 0;
        for (int i=0; i<str.length(); i++) {
            int temp = str.charAt(i) - 'a';
            res = res * 10 + temp;
        }
        return res;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala