LeetCode 2 Add Two Numbers

1年前 (2017-05-11) wang LeetCode 0评论 已收录 231℃ 浏览数:114

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

刚开始看到题目的时候有电不太懂,这是个什么意思。翻译了几次还是有点迷糊。然后去搜索了一下,明白这是一个用链表来存储数据,然后来模拟加法。
这个题目并不难。用一个值来存储进位,然后两个链表进行遍历,哪一个链表的next不为null,取出值,如果为null,则该链表取出的值是0,然后将两个值和进位存储的值进行相加,将尾数存到新的链表中,将进位存起来。然后循环。等到两个链表都遍历结束,判断进位是否为0,如果不为0则保存该值。最后返回这个存储结果的链表。

	public class Solution {
	    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
	    	if(l1 == null && l2 == null){
	    		return null;
	    	}
	    	
	    	ListNode head = new ListNode(0);
	    	ListNode point = head;
	    	int carry = 0;
	    	while(l1 != null || l2 != null){
	    		
	    		int val1 = 0;
	    		if(l1 != null){
	    			val1 = l1.val;
	    			l1 = l1.next;
	    		}
	    		
	    		int val2 = 0;
	    		if(l2 != null){
	    			val2 = l2.val;
	    			l2 = l2.next;
	    		}
	    		
	    		int temp = val1 + val2  + carry;
	    		point.next = new ListNode(temp % 10);
	    		carry = temp / 10;
	    		point = point.next;
	    	}
	    	
	    	if(carry != 0){
	    		 point.next = new ListNode(carry);
	    	}
	    	
	    	return head.next;
	    }
	}

ac以后去查看了大牛写的代码,发现思路都是差不多的,但是我发现别人很擅长用 ?: 这样看起来代码能够简洁很多,起码能缩短一半的长度。而且逻辑性很强,我分了几次进行判断的别人可以直接一次判断。
改进完以后如下

     public class Solution {
	    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
	    	
	    	ListNode head = null,point= null;
	    	point = head =new ListNode(0);
	    	int carry = 0;
	    	while(l1 != null || l2 != null || carry != 0){
	    		int temp = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val)  + carry;
	    		carry = temp / 10;
	    		l1 =(l1 == null ? null : l1.next);
	    		l2 = (l2 == null ? null : l2.next);
	    		point = point.next = new ListNode(temp % 10);
	    	}
	    	
	    	return head.next;
	    }
	}

这样代码就十几行,看着极其的简单明了,逻辑性很强。

博主

Just do it. Now or never.

相关推荐

嗨、骚年、快来消灭0回复。