这篇文章上次修改于 1963 天前,可能其部分内容已经发生变化,如有疑问可询问作者。 >用链表表示10进制的某一位,这样可以计算大数的相加:如 Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. [1]思路:遍历链表,保存进位 ```java /** * 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) { int pre= 0; ListNode r = new ListNode(-1); ListNode p0 = r; ListNode p_1 = null; ListNode p1 = l1; ListNode p2 = l2; while(p1 != null || p2 != null || pre > 0){ int v = p1 ==null ? 0 : p1.val; v = p2 ==null ? v : v + p2.val; v = v + pre; pre = v / 10; if(p1 != null){ p1 = p1.next; } if(p2 != null){ p2 = p2.next; } p0.val = v % 10; p0.next = new ListNode(-1); p_1 = p0; p0 = p0.next; } p_1.next = null; return r; } } ```
没有评论