码迷,mamicode.com
首页 > 其他好文 > 详细

Add Two Numbers

时间:2016-07-16 06:49:14      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1‘s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Example

Given 7->1->6 + 5->9->2. That is, 617 + 295.

Return 2->1->9. That is 912.

Given 3->1->5 and 5->9->2, return 8->0->8.

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;      
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param l1: the first list
15      * @param l2: the second list
16      * @return: the sum list of l1 and l2 
17      */
18     public ListNode addLists(ListNode l1, ListNode l2) {
19         
20         if (l1 == null) return l2;
21         if (l2 == null) return l1;
22         
23         int value1 = 0;
24         int value2 = 0;
25         int carry = 0;
26         ListNode head = new ListNode(0);
27         ListNode current = head;
28         
29         
30         while (l1 != null || l2 != null) {
31             value1 = (l1 == null ? 0 : l1.val);
32             value2 = (l2 == null ? 0 : l2.val);
33             int value = (value1 + value2 + carry) % 10;
34             
35             current.next = new ListNode(value);
36             current = current.next;
37             
38             carry = (value1 + value2 + carry) / 10;
39             l1 = (l1 == null) ? null : l1.next;
40             l2 = (l2 == null) ? null : l2.next;
41         }
42         if (carry == 1) {
43             current.next = new ListNode(carry);
44         }
45         return head.next;
46     }
47 }

 

 

Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5675100.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!