-
[알고리즘] #Add Two Numbers■ Algorithm 2019. 4. 18. 11:06
출처: https://leetcode.com/problems/add-two-numbers/
Add Two Numbers - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
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.
2개의 음수가 아닌 정수를 나타내는 비어있지 않은 linked list가 있습니다. 숫자는 역순으로 저장되고 각 노드는 하나의 숫자를 갖고 있습니다. 두 숫자를 더한 값을 linked list로 나타내세요.
두 숫자에 0을 제외한 leading 0을 갖고 있지 않는다고 가정합니다. (이 부분을 잘 이해를 못했음 ㅠㅠ)
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
header : 제일 첫 번째 ListNode.
currentNode : 각 index의 숫자 합을 저장할 ListNode
header -> currentNode -> currentNode.next -> .... 이런식으로 진행된다고 보면 된다.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode header = new ListNode(0); ListNode tmp1 = l1; ListNode tmp2 = l2; ListNode currentNode = header; int carry = 0; // 두 수의 합이 10 이상인 경우 다음 자릿수로 넘겨줘야할 값 while(tmp1 != null || tmp2 != null) { int t1 = tmp1 != null ? tmp1.val : 0; int t2 = tmp2 != null ? tmp2.val : 0; int sum = carry + t1 + t2; carry = sum/10; currentNode.next = new ListNode(sum%10); currentNode = currentNode.next; if(tmp1 != null) { tmp1 = tmp1.next; } if(tmp2 != null) { tmp2 = tmp2.next; } } if(carry>0){ currentNode.next = new ListNode(carry); } return header.next; } }
'■ Algorithm' 카테고리의 다른 글
[알고리즘] #Validate Binary Search Tree (0) 2019.04.18 [알고리즘] #Same Tree (0) 2019.04.18 [알고리즘] #Two Sum (0) 2019.04.17 [알고리즘] #전화번호 목록 (0) 2019.04.16 [알고리즘] #완주하지 못한 선수 (0) 2019.04.16