首页 > 代码库 > 【LeetCode】2.Add Two Numbers
【LeetCode】2.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 }
【LeetCode】2.Add Two Numbers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。