코딩테스트 풀이/JAVA
[LeetCode/Easy] 1880. Check if Word Equals Summation of Two Words
무지맘
2023. 1. 7. 22:54
1. Input
1) 문자열 firstWord
2) 문자열 secondWord
3) 문자열 targetWord
2. Output
1) firstWord와 secondWord의 값의 합이 targetWord의 값과 같다면 true, 다르면 false를 반환
- ‘a’==0, ‘b’==1, ...
- 문자열 “abc”의 값은 “012” -> 12가 된다.
3. Constraint
1) 1 <= firstWord.length, secondWord.length, targetWord.length <= 8
2) firstWord, secondWord, targetWord에 들어가는 영어 소문자는 [a, j]이다.
4. Example
Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb" -> Output: true
설명:
- "acb" -> "021" -> 21
- "cba" -> "210" -> 210
- "cdb" -> "231" -> 231
- 21 + 210 == 231이므로 true를 반환한다.
5. Code
1) 첫 코드(2022/06/17)
String f = "";
for(int i=0 ; i<firstWord.length() ; i++)
f += firstWord.charAt(i) - 97 + "";
String s = "";
for(int i=0 ; i<secondWord.length() ; i++)
s += secondWord.charAt(i) - 97 + "";
String t = "";
for(int i=0 ; i<targetWord.length() ; i++)
t += targetWord.charAt(i) - 97 + "";
return ( Integer.parseInt(f) + Integer.parseInt(s) ) == Integer.parseInt(t);
2) 다시 풀어본 코드(2023/01/07)
int[] value = new int[3];
for(int i=0 ; i<firstWord.length() ; i++)
value[0] += (firstWord.charAt(i)-97)*Math.pow(10,firstWord.length()-1-i);
for(int i=0 ; i<secondWord.length() ; i++)
value[1] += (secondWord.charAt(i)-97)*Math.pow(10,secondWord.length()-1-i);
for(int i=0 ; i<targetWord.length() ; i++)
value[2] += (targetWord.charAt(i)-97)*Math.pow(10,targetWord.length()-1-i);
return value[0] + value[1] == value[2];
- 성능이 전반적으로 많이 좋아졌다.