星空网 > 软件开发 > Java

【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.

解题思路

这道题目比较简单,设置一个变量保存进位便能得到答案。唯一需要注意的一点是考虑两个链表的长度的情况。还有特别要考虑类似1+9999=10000这样的情况:也就是说,即使一个链表已经遍历完毕,进位与另一个链表对应位置数字相加仍有可能产生进位。

代码如下:

public class Solution {  public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {		if(l1==null)			return l2;		if(l2==null)			return l1;		int len1 = getLength(l1);		int len2 = getLength(l2);		//保证l1链表的长度不小于l2		if(len1<len2){			ListNode l=l1;			l1=l2;			l2=l;		}				int p=0; //用来保存进位		int n=l1.val+l2.val;		p=n/10;		n=n%10;		ListNode head = new ListNode(n);		ListNode current = head;		l1=l1.next;		l2=l2.next;		//还没有扫描完l2的情况		while(l2!=null){			n=l1.val+l2.val+p;			p=n/10;			n=n%10;			ListNode node = new ListNode(n);			current.next=node;			current=node;			l1=l1.next;			l2=l2.next;		}		//扫描完l2的情况		while(l1!=null){			n=l1.val+p;			p=n/10;			n=n%10;			ListNode node = new ListNode(n);			current.next=node;			current=node;			l1=l1.next;		}		//最后是否需要进位		if(p==1){			ListNode node = new ListNode(1);			current.next=node;		}    return head;  }	public static int getLength(ListNode l){		int count=0;		while(l!=null){			count++;			l=l.next;		}		return count;	}}

  




原标题:【leetcode】2. Add Two Numbers

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

深圳到菲律宾货运:https://www.goluckyvip.com/tag/96178.html
快递菲律宾:https://www.goluckyvip.com/tag/96179.html
菲律宾运输:https://www.goluckyvip.com/tag/96180.html
广州 快递 菲律宾:https://www.goluckyvip.com/tag/96181.html
佛山到菲律宾海运:https://www.goluckyvip.com/tag/96182.html
福建到菲律宾快递:https://www.goluckyvip.com/tag/96183.html
九月初新疆旅游服装搭配(新疆游玩必备衣服清单):https://www.vstour.cn/a/408257.html
黄果树瀑布景区景点 - 黄果树瀑布景区景点分布图:https://www.vstour.cn/a/408258.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流