티스토리 뷰
Problem
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
Example 1:
Input: num1 = "11", num2 = "123"
Output: "134"
Example 2:
Input: num1 = "456", num2 = "77"
Output: "533"
Example 3:
Input: num1 = "0", num2 = "0"
Output: "0"
Constraints:
- 1 <= num1.length, num2.length <= 104
- num1 and num2 consist of only digits.
- num1 and num2 don't have any leading zeros except for the zero itself.
Solution
두 개의 음수가 아닌 정수 문자열이 주어질 때 두 수의 합을 구하는 문제입니다.
public class Solution {
public String addStrings(String num1, String num2) {
int n = num1.length();
int m = num2.length();
StringBuilder result = new StringBuilder();
int carry = 0;
for (int i = 0; i < Math.max(n, m); i++) {
int c1 = n - 1 - i >= 0 ? num1.charAt(n - 1 - i) - '0' : 0;
int c2 = m - 1 - i >= 0 ? num2.charAt(m - 1 - i) - '0' : 0;
int c = c1 + c2 + carry;
if (c >= 10) {
c -= 10;
carry = 1;
} else {
carry = 0;
}
result.append(c);
}
if (carry != 0) {
result.append(carry);
}
return result.reverse().toString();
}
}
숫자의 길이가 10^4까지이기 때문에 단순히 숫자로 파싱한 다음 더하는 게 아니라 각 자리 수를 더해주는 방법을 사용해야 합니다.
두 수의 자리수 차이가 있을 수 있어 그 부분에 대한 예외처리만 추가하면 간단하게 해결할 수 있습니다.
Test
package io.lcalmsky.leetcode.add_strings;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
public void givenTwoStrings_whenAddThem_thenCorrect() {
assertAll(
() -> test("11", "123", "134"),
() -> test("456", "77", "533"),
() -> test("0", "0", "0")
);
}
private void test(String num1, String num2, String expected) {
// when
Solution addStrings = new Solution();
String actual = addStrings.addStrings(num1, num2);
// then
assertEquals(expected, actual);
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
814. Binary Tree Pruning (0) | 2022.09.08 |
---|---|
429. N-ary Tree Level Order Traversal (0) | 2022.09.07 |
967. Numbers With Same Consecutive Differences (0) | 2022.09.04 |
1448. Count Good Nodes in Binary Tree (0) | 2022.09.02 |
869. Reordered Power of 2 (0) | 2022.08.31 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Spring Data JPA
- Java
- spring boot app
- gRPC
- Jackson
- @ManyToOne
- 스프링 부트 튜토리얼
- Spring Boot
- intellij
- 스프링 데이터 jpa
- Spring Boot JPA
- leetcode
- JPA
- 스프링부트
- r
- 함께 자라기
- spring boot application
- Linux
- 스프링 부트
- QueryDSL
- 스프링 부트 애플리케이션
- 클린 아키텍처
- spring boot jwt
- 알고리즘
- 헥사고날 아키텍처
- proto3
- 함께 자라기 후기
- 스프링 부트 회원 가입
- JSON
- Spring Boot Tutorial
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함