leetcode 2. Add Two Numbers

一 题目

Medium

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

二 分析

就是两个链表表示的数相加,考虑到链表的特性,也是从低位想高位操作。看起来有点怪怪的。

我觉得,主要考虑到求和对10求余,以及进位的问题。

还有边界的判定,可能list不一样一样长度(位数不同),如下所示:

[1,8]
[0]

对于取不到的,val默认为0.

还有一种case,就是最后一位想高位进位了。

/**
 * 
 * @author bohu83
 * 2019-08-25
 */
public class AddTwoNumbersTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ListNode l1 = new ListNode(2);
		ListNode l11 = new ListNode(4);
		ListNode l111 = new ListNode(3);
		l1.next = l11;
		l11.next = l111;
		ListNode l2 = new ListNode(5);
		ListNode l21 = new ListNode(6);
		ListNode l211 = new ListNode(4);
		l2.next = l21;
		l21.next = l211;
		ListNode res =addTwoNumbers(l1,l2);
		while(res != null){
		System.out.print(res.val+"->");
		res = res.next;
		}
	}

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    	
    	  
    	  ListNode res =new ListNode(0);
    	  int tmp = 0;
    	  ListNode cur= res; 
    	 while(l1!= null|| l2 != null){    		
    		 int n1 = l1.val;
    		 int n2 = l2.val;
    		 
    		 cur.next = new ListNode((n1+n2+tmp)%10);
			 cur = cur.next;
			 
			 if(n1+n2+tmp>=10){    				
				 tmp=1;
			 }else{ 		
				 tmp =0;
			 }			
    		 
    		if(l1 != null) l1 = l1.next;
    		if(l2 != null) l2 = l2.next;
    	 }
    	 //进位的情况
    	 if(tmp>0){
    		 cur.next = new ListNode(tmp);
    	 }
    	
		return res.next;
    }
	
	
}
 class ListNode {
	     int val;
	      ListNode next;
	      ListNode(int x) { val = x; }
	  }

我开在一个地方,初始值的更改。几次都失败。看了官网的solution之后,使用了空的节点,处理得很优雅。

效果还是不错的。

Runtime: 2 ms, faster than 80.47% of Java online submissions for Add Two Numbers.

Memory Usage: 44.8 MB, less than 85.58% of Java online submissions forAdd Two Numbers.

时间复杂度:O(max(m,n)),m 和 n 代表 l1 和 l2 的长度。

空间复杂度:O(max(m,n)),m 和 n 代表 l1 和 l2 的长度。而其实新的 List 最大长度是 O(max(m,n))+ 1(进位的case)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值