首页 > 其他 > 详细

Add Two Numbers

时间:2015-05-03 11:47:47      阅读:220      评论:0      收藏:0      [点我收藏+]

https://leetcode.com/problems/add-two-numbers/

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

 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 static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
11     int j=0,x,y;
12     ListNode an=new ListNode(0);
13     ListNode p=an;
14     while(l1!=null||l2!=null){
15         if(l1!=null){x=l1.val;l1=l1.next;}
16         else x=0;
17         if(l2!=null){y=l2.val;l2=l2.next;}
18         else y=0;
19         
20         int re=x+y+j;
21         if(re>=10){re-=10;j=1;}
22         else j=0;
23         ListNode node=new ListNode(re);
24         p.next=node;p=node;
25     }
26     if(j==1){
27         ListNode node=new ListNode(1);
28         p.next=node;
29     }
30     return an.next;
31         
32     }
33 }

 

Add Two Numbers

原文:http://www.cnblogs.com/qq1029579233/p/4473438.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!