LeetCode 2 — Add Two Numbers(C++ Java Python)

來源:互聯網
上載者:User

題目:http://oj.leetcode.com/problems/add-two-numbers/

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

題目翻譯:

給定兩個鏈表表示兩個非負數。數字逆序儲存,每個節點包含一個單一的數字。計算兩個數的和,並以鏈表的形式返還。 分析:

        要考慮進位。表示結果的結點要new出來。

C++實現:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.if (l1 == NULL){return l2;}if (l2 == NULL){return l1;}ListNode *result = NULL;ListNode *sum = NULL;int val = 0;int carry = 0;while (l1 != NULL || l2 != NULL){val = carry;if (l1 != NULL){val += l1->val;}if (l2 != NULL){val += l2->val;}carry = val / 10;val -= carry * 10;if (sum == NULL){sum = new ListNode(val);result = sum;}else{sum->next = new ListNode(val);sum = sum->next;}if (l1 != NULL)  {l1 = l1->next;}if (l2 != NULL){l2 = l2->next;}}if (carry != 0){sum->next = new ListNode(carry);}return result;    }};

Java實現:(與C++實現不太一樣)

/** * 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) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.if (l1 == null) {return l2;}if (l2 == null) {return l1;}int len1 = 0;int len2 = 0;ListNode head = l1;while (head != null) {++len1;head = head.next;}head = l2;while (head != null) {++len2;head = head.next;}ListNode longer = len1 >= len2 ? l1 : l2;ListNode shorter = len1 < len2 ? l1 : l2;ListNode result = null;ListNode sum = null;int val = 0;int carry = 0;while (shorter != null) {val = longer.val + shorter.val + carry;carry = val / 10;val -= carry * 10;if (sum == null) {sum = new ListNode(val);result = sum;} else {sum.next = new ListNode(val);sum = sum.next;}longer = longer.next;shorter = shorter.next;}while (longer != null) {val = longer.val + carry;carry = val / 10;val -= carry * 10;sum.next = new ListNode(val);sum = sum.next;longer = longer.next;}if (carry != 0) {sum.next = new ListNode(carry);}return result;    }}

Python實現:

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # @return a ListNode    def addTwoNumbers(self, l1, l2):        if l1 == None:            return l2        if l2 == None:            return l1                len1 = 0        len2 = 0                head = l1        while head != None:            len1 += 1            head = head.next                head = l2        while head != None:            len2 += 1            head = head.next                if len1 >= len2:            longer = l1            shorter = l2        else:            longer = l2;            shorter = l1                sum = None                carry = 0                while shorter != None:            value = longer.val + shorter.val + carry            carry = value / 10            value -= carry * 10                        if sum == None:                sum = ListNode(value)                result = sum            else:                sum.next = ListNode(value)                sum = sum.next                            longer = longer.next            shorter = shorter.next                    while longer != None:            value = longer.val + carry            carry = value / 10            value -= carry * 10                        sum.next = ListNode(value)            sum = sum.next                        longer = longer.next                    if carry != 0:            sum.next = ListNode(carry)                return result

        感謝閱讀,歡迎評論。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.