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

LC.02. Add Two Numbers

时间:2018-02-23 13:20:41      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:esc   bsp   sts   des   not   turn   git   dig   post   

https://leetcode.com/problems/add-two-numbers/description/
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.

Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

We have l1=343, l2=261 when add(l1,l2) we have 3+2=5, 4+6=10 /10=1 1 carry to next,
second digit set to (10%10=0) 0, 3+1=4 but 4 + carry = 5, add(l1,l2) = 505


 1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
 2         ListNode dummy = new ListNode(0);
 3         int sum =0 ;
 4         ListNode curr = dummy ;
 5         ListNode p1 = l1, p2 = l2 ;
 6         while (p1 != null || p2 != null){
 7             if (p1 != null){
 8                 sum += p1.val ;
 9                 p1 = p1.next ;
10             }
11             if (p2 != null){
12                 sum += p2.val ;
13                 p2 = p2.next;
14             }
15             curr.next = new ListNode(sum %10) ;  //10 %10 =0
16             sum /=10 ; //7/10 =0, 10/10 =1  11/10 =1
17             curr = curr.next ;
18         }
19         /*  642 + 465
20         * if (2 -> 4 -> 6) + (5 -> 6 -> 4)
21         *    2+5 = 7 node:7
22         *    4+ 6 = 10, node: 0 carry 1
23         *    6+4+1 = 11 node: 1 carry 1   === this needs special treatment
24         *    链表连成: 7011   系统自动转换成: 1107
25         * */
26         //两位数想加 最大进1位  不可能最后成2
27         if (sum == 1){
28             curr.next = new ListNode(1) ;
29         }
30         return dummy.next ;
31     }

 

LC.02. Add Two Numbers

标签:esc   bsp   sts   des   not   turn   git   dig   post   

原文地址:https://www.cnblogs.com/davidnyc/p/8461365.html

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