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

[Leet code 2]Two Sum

时间:2015-04-06 17:01:05      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

1 题目

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

 

Hide Tags
 Linked List Math
2 思路
因为之前做过类似的,刚开始想的就是变为连起来的数字相加。但是,这是不行的,因为链表长度足够长的话,变回越界。
 
这道题可以直接取两个链表的值,相加即可。唯一考虑的只是进位而已。说起来简单,但实现起来并不容易。下面是一种思路:
像归并排序最后连起来一样的思路。
 
3 代码
 
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode headNode = new ListNode(0);
        ListNode p = headNode;
        int carry = 0;
        
        while (l1 != null && l2 != null) {
            int var = l1.val + l2.val + carry;
            carry = var / 10;
            var = var % 10;
            
            ListNode node = new ListNode(var);
            
            p.next = node;
            p = p.next;
            
            l1 = l1.next;
            l2 = l2.next;
            
        }
        //要考虑到前面可能有进位,要加上carry
        while (l1 != null) {
            int var = l1.val + carry;
            carry = var /10;
            var = var % 10;
            ListNode node = new ListNode(var);
            p.next = node;
            p = p.next;
            l1 = l1.next;
        }
        
        while (l2 != null) {
            int var = l2.val + carry;
            carry = var /10;
            var = var % 10;
            ListNode node = new ListNode(var);
            p.next = node;
            p = p.next;
            l2 = l2.next;
        }
        //要考虑到最后有个进位,就新建一个节点
        if (carry != 0) {
            ListNode node = new ListNode(carry);
            p.next = node;
            p = p.next;
        }
        return headNode.next;
    }
}

 

[Leet code 2]Two Sum

标签:

原文地址:http://www.cnblogs.com/lingtingvfengsheng/p/4396152.html

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