반응형
2. Add Two Numbers (Medium)
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Java Solution
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode answer = new ListNode(l1.val);
ListNode temp = answer;
while(l1.next != null) {
temp.next = new ListNode(l1.next.val);
l1 = l1.next;
temp = temp.next;
}
int p = 0;
temp = answer;
while(l2 != null || p == 1) {
int sum = l2 != null ? temp.val + l2.val : temp.val;
p = sum >= 10 ? 1 : 0;
temp.val = sum % 10;
if(p == 1) {
if(temp.next != null) {
temp.next.val += p;
} else {
temp.next = new ListNode(p);
}
}
l2 = l2 != null ? l2.next : null;
temp.next = temp.next == null ? (l2 != null ? new ListNode(0) : null) : temp.next;
temp = temp.next;
}
return answer;
}
}
Kotlin Solution
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
var tmp1: ListNode? = l1
var tmp2: ListNode? = l2
var carry: Int = 0
val ans = ListNode(-1)
var tmpAns = ans
while(tmp1 != null || tmp2 != null || carry > 0) {
var cal = 0
tmp1?.let {
cal += it.`val`
tmp1 = it.next
}
tmp2?.let {
cal += it.`val`
tmp2 = it.next
}
cal += carry
if(cal >= 10) {
carry = 1
cal %= 10
} else {
carry = 0
}
tmpAns.next = ListNode(cal)
tmpAns = tmpAns.next!!
}
return ans.next
}
}
이 외에도 다양한 문제들의 해답 코드를 깃헙 저장소에서 확인할 수 있습니다. (Java, Kotlin)
반응형
'Algorithm' 카테고리의 다른 글
[Leetcode] 4번 - Median of Two Sorted Arrays (Java, Kotlin) (0) | 2020.03.29 |
---|---|
[Leetcode] 3번 - Longest Substring Without Repeating Characters (Java, Kotlin) (0) | 2020.03.28 |
[LeetCode] 1번 - Two Sum (Java, Kotlin) (0) | 2020.03.26 |
알고리즘 사이트 비교 및 추천 (4) | 2019.11.10 |
[백 트래킹][백준 1948번] N과 M(1) - Java (0) | 2019.10.03 |