码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode -- Add Two Numbers

时间:2015-10-14 00:28:13      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:


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


同时遍历两个链表,对每个节点分别求和,每个节点只存1位结果,保留进位用于下一个节点计算。


思路:
1.两个指针分别指向链表1(l1)和链表2(l2)的首位,逐位计算即可。
2.存首节点以及当链表遍历之后,还有carry没有放入链表的情况。



/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
        ListNode node = null;        
    	ListNode head = null;
    	
    	var carry = 0;
    	while(l1 != null || l2 != null){
    		
    		var a = l1 != null ? l1.val : 0;
    		var b = l2 != null ? l2.val : 0;
    		
    		var s = a + b + carry;
    		var r = s % 10;
    		if(node == null){
    			node = new ListNode(r);
    			head = node;
    		}else{
    			node.next = new ListNode(r);
    			node = node.next;
    		}
    		carry = s / 10;
    		
    		if(l1 != null){
    			l1 = l1.next;
    		}
    		if(l2 != null){
    			l2 = l2.next;
    		}
    	}
    	
    	if(carry > 0){
    		var n = new ListNode(carry);
    		node.next = n;
    	}
    	
    	return head;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode -- Add Two Numbers

标签:

原文地址:http://blog.csdn.net/lan_liang/article/details/49108345

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!