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

Add Two Numbers

时间:2015-05-03 11:48:50      阅读:122      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!