|
| 1 | +// LeetCode_2 |
| 2 | +// 2020.04.12 |
| 3 | +// List, case work |
| 4 | +// Medium |
| 5 | + |
| 6 | +public class AddTwoNum { |
| 7 | + public static void main(String[] args) { |
| 8 | + new ListNode().printListNode(new AddTwoNum().addTwoNumbers( |
| 9 | + new ListNode(2, new ListNode(4, new ListNode(3))), |
| 10 | + new ListNode(5, new ListNode(6, new ListNode(4))))); |
| 11 | + } |
| 12 | + |
| 13 | + public ListNode addTwoNumbers(ListNode l1, ListNode l2) throws NumberFormatException{ |
| 14 | + long num1 = 0, num2 = 0; |
| 15 | + ListNode listNode = new ListNode(); |
| 16 | + ListNode head = listNode; |
| 17 | + |
| 18 | + while (l1 != null) { |
| 19 | + num1 += l1.val; |
| 20 | + if (l1.next != null) |
| 21 | + num1 *= 10; |
| 22 | + l1 = l1.next; |
| 23 | + } |
| 24 | + while (l2 != null) { |
| 25 | + num2 += l2.val; |
| 26 | + if (l2.next != null) |
| 27 | + num2 *= 10; |
| 28 | + l2 = l2.next; |
| 29 | + } |
| 30 | + StringBuffer str1 = new StringBuffer(String.valueOf(num1)); |
| 31 | + StringBuffer str2 = new StringBuffer(String.valueOf(num2)); |
| 32 | + str1.reverse(); |
| 33 | + str2.reverse(); |
| 34 | + num1 = Long.valueOf(String.valueOf(str1)); |
| 35 | + num2 = Long.valueOf(String.valueOf(str2)); |
| 36 | + num1 += num2; |
| 37 | + |
| 38 | + |
| 39 | + while (num1 != 0) { |
| 40 | + listNode.val = num1 % 10; |
| 41 | + num1 /= 10; |
| 42 | + if (num1 == 0) |
| 43 | + break; |
| 44 | + listNode.next = new ListNode(); |
| 45 | + listNode = listNode.next; |
| 46 | + } |
| 47 | + |
| 48 | + return head; |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +// Best Solution-O(max(n,m))_출처 leetcode |
| 53 | +// |
| 54 | +// public ListNode addTwoNumbers(ListNode l1, ListNode l2) { |
| 55 | +// ListNode dummyHead = new ListNode(0); |
| 56 | +// ListNode p = l1, q = l2, curr = dummyHead; |
| 57 | +// int carry = 0; |
| 58 | +// while (p != null || q != null) { |
| 59 | +// int x = (p != null) ? p.val : 0; |
| 60 | +// int y = (q != null) ? q.val : 0; |
| 61 | +// int sum = carry + x + y; |
| 62 | +// carry = sum / 10; |
| 63 | +// curr.next = new ListNode(sum % 10); |
| 64 | +// curr = curr.next; |
| 65 | +// if (p != null) p = p.next; |
| 66 | +// if (q != null) q = q.next; |
| 67 | +// } |
| 68 | +// if (carry > 0) { |
| 69 | +// curr.next = new ListNode(carry); |
| 70 | +// } |
| 71 | +// return dummyHead.next; |
| 72 | +// } |
0 commit comments