반응형
문제
내 답
- 1시간 제한
- 인터넷 사용 안함
내 코드
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int num1Leng = num1.length() - 1;
int num2Leng = num2.length() - 1;
int round = 0;
for (int i = Math.max(num1.length(), num2.length()) - 1; i > -1; --i) {
if (num1Leng < 0) {
sb.append(String.valueOf(((num2.charAt(num2Leng) - 48) + round)%10));
if ((((num2.charAt(num2Leng) - 48) + round)/10) > 0) {
round=1;
}else{
round=0;
}
} else if (num2Leng < 0) {
sb.append(String.valueOf(((num1.charAt(num1Leng) - 48) + round)%10));
if ((((num1.charAt(num1Leng) - 48) + round)/10) > 0) {
round=1;
}else{
round=0;
}
} else {
sb.append(String.valueOf((((num1.charAt(num1Leng) - 48 + num2.charAt(num2Leng) - 48+round) % 10))));
if ((((num1.charAt(num1Leng) - 48 + num2.charAt(num2Leng) - 48)+round) / 10) > 0) {
round=1;
}else{
round=0;
}
}
--num1Leng;
--num2Leng;
}
if(round != 0){
sb.append("1");
}
return sb.reverse().toString();
}
}
- Time complexity : O(max(n,m))O(max(n,m))
- Space complexity : O(1)O(1)
최선의 답
인터넷과 책에서 찾아본 답
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int index1 = num1.length() - 1;
int index2 = num2.length() - 1;
int round = 0;
//두개의 인덱스가 전부 -1이 될때까지 루프합니다.
//결과 적으로 input중 문자수가 가장 많은 문자열의 인덱스만큼 반복합니다.
//인덱스는 뒤에서 부터 시작해서 하나씩 줄어듭니다.
while (index1 >= 0 || index2 >= 0) {
//인덱스가 0보다 작으면 0을 주고, 아니라면 문자를 숫자로 변경해서 리턴합니다.
int temp1 = index1 < 0 ? 0 : num1.charAt(index1) - '0';
int temp2 = index2 < 0 ? 0 : num2.charAt(index2) - '0';
sb.insert(0, (temp1 + temp2 + round) % 10);//가장 왼쪽에 올림할 수를 버리고 추가합니다.
round = (temp1 + temp2 + round) / 10;//올림하는 수를 저장해서 다음루프에 사용합니다.
--index1;
--index2;
}
if(round != 0){//마지막 올림하는 수는 루프에 포함이 되지 않으므로, 있다면 추가합니다.
sb.insert(0,"1");
}
return sb.toString();//stringBuilder를 String으로 형변환하고 리턴합니다.
}
}
- Time complexity : O(max(n,m))O(max(n,m))
- Space complexity : O(1)O(1)
반성 할 점
- 기본 알고리즘과 스트링빌더를 사용하는건 맞지만, 내가 짠 코드는 최적화가 되지 않음.
- ternary conditional operator는 자바 8 이상에서만 사용가능함.
반응형
'old > Algorithm Solving' 카테고리의 다른 글
Wave Array문제의 자바 해결 방법: 효율적인 알고리즘 (0) | 2023.04.24 |
---|---|
Geekina Loves Order 문제의 자바 솔루션 (0) | 2023.04.05 |
Remove Duplicates from Sorted Array 문제풀이 (0) | 2021.09.11 |
Two Sum문제 풀이 (0) | 2021.09.09 |
Count Binary Substrings문제 풀이 (0) | 2021.09.09 |