LeetCode2.Add Two Numbers

Posted 一只笨笨鸟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode2.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

思路:采用递归思想。设置一个carray变量用于存放进位值,将l1,l2,carray相加,十进制取余得到该位的值,进行链表下一位运算。

 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 ListNode addTwoNumbers(ListNode l1, ListNode l2) {
11         return addTwoNumbersHelp(l1,l2,0);
12     }
13     
14     public ListNode addTwoNumbersHelp(ListNode l1,ListNode l2,int carray){
15         if(l1==null && l2==null){
16             return carray==0?null:new ListNode(carray);
17         }
18         
19         if(l1==null && l2!=null){
20             l1=new ListNode(0);
21         }
22         
23         if(l1!=null && l2==null){
24             l2=new ListNode(0);
25         }
26         
27         int sum=l1.val+l2.val+carray;
28         ListNode curr=new ListNode(sum%10);
29         curr.next=addTwoNumbersHelp(l1.next,l2.next,sum/10);
30         
31         return curr;
32     }

 


以上是关于LeetCode2.Add Two Numbers的主要内容,如果未能解决你的问题,请参考以下文章

leetcode2. Add Two Numbers

leetcode2. Add Two Numbers

Leetcode2. Add Two Numbers

Leetcode2 Add Two Numbers

Leetcode2. Add Two Numbers 两数相加

leetcode2 add two numbers