Skip to content

1880. Check if Word Equals Summation of Two Words 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  bool isSumEqual(string firstWord, string secondWord, string targetWord) {
    const int first = getNumber(firstWord);
    const int second = getNumber(secondWord);
    const int target = getNumber(targetWord);
    return first + second == target;
  }

 private:
  int getNumber(const string& word) {
    int num = 0;
    for (const char c : word)
      num = num * 10 + (c - 'a');
    return num;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
    final int first = getNumber(firstWord);
    final int second = getNumber(secondWord);
    final int target = getNumber(targetWord);
    return first + second == target;
  }

  private int getNumber(String word) {
    int num = 0;
    for (final char c : word.toCharArray())
      num = num * 10 + (c - 'a');
    return num;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
    first = self._getNumber(firstWord)
    second = self._getNumber(secondWord)
    target = self._getNumber(targetWord)
    return first + second == target

  def _getNumber(self, word: str) -> int:
    num = 0
    for c in word:
      num = num * 10 + (ord(c) - ord('a'))
    return num