[Leetcode]2. Add Two Numbers
阿新 • • 發佈:2021-01-12
題目描述
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 contains a single digit. Add the two numbers and return the sumas a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
- Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
- Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
- Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
給定兩個連結串列,每個連結串列倒序儲存著數字,兩個數字求和,返回新的連結串列。
java解法
public class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } static ListNode of(int[] nums) { ListNode dummyHead = new ListNode(-1); for (int i = nums.length - 1; i >= 0; i--) { dummyHead.next = new ListNode(nums[i], dummyHead.next); } return dummyHead.next; } @Override public String toString() { ListNode cur = this; StringBuilder buffer = new StringBuilder(); while (cur != null) { buffer.append(cur.val).append("->"); cur = cur.next; } return buffer.toString(); } }
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode curL1 = l1; ListNode curL2 = l2; //進位 int carry = 0; ListNode dummyHead = new ListNode(-1); ListNode cur = dummyHead; while (curL1 != null || curL2 != null) { int val1 = curL1 == null ? 0 : curL1.val; int val2 = curL2 == null ? 0 : curL2.val; int val = val1 + val2 + carry; cur.next = new ListNode(val % 10); carry = val / 10; if (curL1 != null) { curL1 = curL1.next; } if (curL2 != null) { curL2 = curL2.next; } cur = cur.next; } if (carry == 1) { cur.next = new ListNode(1); } return dummyHead.next; } public static void main(String[] args) { ListNode l1 = ListNode.of(new int[]{9, 9, 9, 9, 9, 9, 9}); ListNode l2 = ListNode.of(new int[]{9, 9, 9, 9}); ListNode listNode = new Solution().addTwoNumbers(l1, l2); System.out.println(l1); System.out.println(l2); System.out.println(listNode); } }