首页 > 代码库 > Add Two Numbers

Add Two Numbers

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

 

在l1上操作,20%,注意应该用l1还是l1.next去做判断

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
11         int c = 0;
12         ListNode dump = l1;
13         while (l1.next != null && l2.next != null) {
14             int sum = l1.val + l2.val + c; 
         //这个地方,要写成sum,不能直接用表达式,l1.val = (l1.val + l2.val +c) % 10; c = (l1.val + l2.val + c) / 10;
15 l1.val = sum % 10; 16 c = sum / 10; 17 l1 = l1.next; 18 l2 = l2.next; 19 } 20 l1.val = l1.val + l2.val; 21 if (l1.next == null) { 22 l1.next = l2.next; 23 24 } 25 26 while (l1.next != null) { 27 int sum = l1.val + c; 28 l1.val = sum % 10; 29 c = sum /10; 30 l1 = l1.next; 31 } 32 if (l1.val + c < 10) { 33 l1.val = l1.val + c; 34 } else { 35 int sum = l1.val + c; 36 l1.val = sum % 10; 37 l1.next = new ListNode (sum / 10); 38 } 39 return dump; 40 } 41 }

 

九章的解法,40%

 1 public class Solution {
 2     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
 3         if(l1 == null && l2 == null) {
 4             return null;
 5         }
 6             
 7         ListNode head = new ListNode(0);
 8         ListNode point = head;
 9         int carry = 0;
10         while(l1 != null && l2!=null){
11             int sum = carry + l1.val + l2.val;
12             point.next = new ListNode(sum % 10);
13             carry = sum / 10;
14             l1 = l1.next;
15             l2 = l2.next;
16             point = point.next;
17         }
18         
19         while(l1 != null) {
20             int sum =  carry + l1.val;
21             point.next = new ListNode(sum % 10);
22             carry = sum /10;
23             l1 = l1.next;
24             point = point.next;
25         }
26         
27         while(l2 != null) {
28             int sum =  carry + l2.val;
29             point.next = new ListNode(sum % 10);
30             carry = sum /10;
31             l2 = l2.next;
32             point = point.next;
33         }
34         
35         if (carry != 0) {
36             point.next = new ListNode(carry);
37         }
38         return head.next;
39     }
40 }

 

Add Two Numbers