You are given two linked lists representing two non-negative numbers. 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.Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8
初次看题没懂。
要点是 each of their nodes contain a single digit.
上面的例子是:
2+5=7;
4+6=10;10不满足 a single digit条件,0保存到当前结点中,进位1就要保存到下一个结点。
思路:
思路非常简单,分别遍历两个链表,并且用一个变量表示是否有进位。某个链表遍历结束之后再将另一个链表连接在结果链表之后即可,若最后有进位需要添加一位。
给出一种解答:Runtime: 420 ms
head 相当于头指针,方便遍历结果链表
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode result = new ListNode(0); ListNode head = result; int sum = 0; int carry = 0;//jin wei while(l1 != null || l2 != null) { int val1 = 0; if(l1 != null){ val1 = l1.val; l1 = l1.next; } int val2 = 0; if(l2 != null) { val2 = l2.val; l2 = l2.next; } sum = val1 + val2 + carry; result.next = new ListNode(sum%10); result = result.next; carry = sum/10; } if(carry == 1){ result.next = new ListNode(1); } return head.next; }}
九章算法网给出的答案是:
Runtime: 540 ms
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1 == null && l2 == null) { return null; } ListNode head = new ListNode(0); ListNode point = head; int carry = 0; while(l1 != null && l2!=null){ int sum = carry + l1.val + l2.val; point.next = new ListNode(sum % 10); carry = sum / 10; l1 = l1.next; l2 = l2.next; point = point.next; } while(l1 != null) { int sum = carry + l1.val; point.next = new ListNode(sum % 10); carry = sum /10; l1 = l1.next; point = point.next; } while(l2 != null) { int sum = carry + l2.val; point.next = new ListNode(sum % 10); carry = sum /10; l2 = l2.next; point = point.next; } if (carry != 0) { point.next = new ListNode(carry); } return head.next; }}