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

LeetCode-Add Two Numbers

时间:2015-04-17 07:06:41      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

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

Hide Tags Linked List Math

这道题在原理上很简单,模拟了加法的运算。但如何使code写的简洁是个难点,另外运用到了前置节点和遍历节点的技术。

 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     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
14         if(l1==null && l2 == null){
15             return null;
16         }
17         else if(l1 != null && l2 == null){
18             return l1;
19         }
20         else if(l2 != null && l2 == null){
21             return l2;
22         }
23         
24         ListNode dummy = new ListNode(-1);
25         ListNode end = dummy;
26         int carry =0;
27         while(l1 != null || l2 != null || carry !=0){
28             int current =0;
29             if(l1 != null){
30                 current = current + l1.val;
31                 l1 = l1.next;
32             }
33             if(l2 != null){
34                 current = current +l2.val;
35                 l2 = l2.next;
36             }
37             if(carry !=0 ){
38                 current = current + carry;
39             }
40             
41             end.next = new ListNode(current%10);
42             carry = current / 10;
43             end = end.next;
44         }
45         return dummy.next;
46         
47     }
48 }

 

LeetCode-Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/incrediblechangshuo/p/4433834.html

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