资讯专栏INFORMATION COLUMN

[LintCode/LeetCode] Add Two Numbers

hedzr / 251人阅读

Problem

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1"s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Example

Given 7->1->6 + 5->9->2. That is, 617 + 295.

Return 2->1->9. That is 912.

Given 3->1->5 and 5->9->2, return 8->0->8.

Note

[null]

Solution
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int sum = carry;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            carry = sum/10;
            head.next = new ListNode(sum%10);
            head = head.next;
        }
        if (carry != 0) head.next = new ListNode(carry);
        return dummy.next;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65688.html

相关文章

  • [LintCode/LeetCode] Two Sum

    摘要:就不说了,使用的解法思路如下建立,对应该元素的值与之差,对应该元素的。然后,循环,对每个元素计算该值与之差,放入里,。如果中包含等于该元素值的值,那么说明这个元素正是中包含的对应的差值。返回二元数组,即为两个所求加数的序列。 Problem Given an array of integers, find two numbers such that they add up to a s...

    xiaoxiaozi 评论0 收藏0
  • [LintCode/LeetCode] Subsets & Subsets II

    Subsets Problem Given a set of distinct integers, return all possible subsets. Notice Elements in a subset must be in non-descending order.The solution set must not contain duplicate subsets. Example ...

    tracy 评论0 收藏0
  • [LintCode/LeetCode] Single Number III

    摘要:去掉最后一个保留最后一个保留最后一个保留第一个这道题在论坛里参考了和两位仁兄的解法。思想是将中所有的数进行异或运算。不同的两个数异或的结果,一定至少有一位为。最后,将和存入数组,返回。 Problem Given 2*n + 2 numbers, every numbers occurs twice except two, find them. Example Given [1,2,2...

    lanffy 评论0 收藏0
  • [LintCode/LeetCode] Combinations

    摘要:题目为求从到的自然数里取个数的所有组合全集。使用递归的模板,建立函数。模板如下也可以不建立新的,而是递归调用之后删去中最后一个元素 Problem Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. Example For example,If n = 4 a...

    Raaabbit 评论0 收藏0
  • [LintCode/LeetCode] Find Median From / Data Stream

    摘要:建立两个堆,一个堆就是本身,也就是一个最小堆另一个要写一个,使之成为一个最大堆。我们把遍历过的数组元素对半分到两个堆里,更大的数放在最小堆,较小的数放在最大堆。同时,确保最大堆的比最小堆大,才能从最大堆的顶端返回。 Problem Numbers keep coming, return the median of numbers at every time a new number a...

    zxhaaa 评论0 收藏0

发表评论

0条评论

hedzr

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<