2. Add Two Numbers

原创 2015年11月20日 09:31:27

题意:两个整数用list表示,求他们的和,高位在list尾部

思路:
遍历两个list,每次把两个数,及进位相加,当前数为和求余10,进位为和除以10,知道有一个list结束,并查看两个list,把没有遍历完的list中的元素放到结果list的后边,其中要注意进位

时间:O(n)
空间:O(n+m)

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode newhead = new ListNode(0);
        ListNode runner = newhead;
        int carrier = 0;
        while(l1!=null&&l2!=null)
        {
            int cur = l1.val+l2.val+carrier;
            runner.next = new ListNode(cur%10);
            carrier = cur/10;
            l1 = l1.next;
            l2 = l2.next;
            runner = runner.next;
        }
        while(l1!=null)
        {
            int cur = l1.val + carrier;
            runner.next = new ListNode(cur%10);
            carrier = cur/10;
            l1 = l1.next;
            runner = runner.next;
        }

        while(l2!=null)
        {
            int cur = l2.val + carrier;
            runner.next = new ListNode(cur%10);
            carrier = cur/10;
            l2 = l2.next;
            runner = runner.next;
        }

        if(carrier!=0)
        {
            runner.next = new ListNode(carrier);
        }

        return newhead.next;
    }
}

2. Add Two Numbers官方通过版本(8.46%)

public class AddTwoNumbers { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { Lis...
  • ithouse
  • ithouse
  • 2016年01月05日 15:58
  • 210

Leetcode: Add Two Numbers (2)

You are given two linked lists representing two non-negative numbers. The digits are stored in orde...
  • lzmaths
  • lzmaths
  • 2013年12月18日 14:19
  • 403

LeetCode Algorithms 2. Add Two Numbers 题解

题目: You are given two non-empty linked lists representing two non-negative integers. The digits...

LeetCode#2 Add Two Numbers

题目:You are given two non-empty linked lists representing two non-negative integers. The digits are s...

leetcode 2. Add Two Numbers

1.题目描述                                                                                              ...

算法设计Week1 LeetCode Algorithms Problem #2 Add Two Numbers

题目描述 You are given two non-empty linked lists representing two non-negative integers. The digits...

leetCode 2 Add Two Numbers

问题:Add Two Numbers You are given two linked lists representing two non-negative numbers. The digits...

Leetcode 2. Add Two Numbers

leetcode页面样式换了,标题和total accepted也截不到了。就直接粘描述吧 You are given two linked lists representing two non-n...

leetcode #2 Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in rever...

2. Add Two Numbers(Medium)

原题目:   You are given two non-empty linked lists representing two non-negative integers. The digits ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:2. Add Two Numbers
举报原因:
原因补充:

(最多只允许输入30个字)