国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LintCode/LeetCode] Add Two Numbers

hedzr / 389人閱讀

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;
    }
}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/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元查看
<