zoukankan      html  css  js  c++  java
  • leetcode2. Add Two Numbers

    leetcode2. Add Two Numbers

    题意:

    给定两个非空的链表,表示两个非负整数。数字以相反的顺序存储,每个节点包含一个数字。添加两个数字并将其作为链表返回。

    你可以假设两个数字不包含任何前导零,除了数字0本身。

    思路:

    O(n)遍历两个链表,两个节点和一个carry(用于记录前面相加大于10的变量)相加放入res链表中,记录除数和余数直到遍历结束。

    ac代码:

    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) {
            int up=0;
            ListNode node = ListNode(0);
            ListNode* head = &node;
            while(l1||l2||up)
            {
                int temp = (l1?l1->val:0)+(l2?l2->val:0)+up;
                head->next = new ListNode(temp%10);
                up = temp/10;
                head = head->next;
                l1 = l1?l1->next:l1;
                l2 = l2?l2->next:l2;
            }
            return node.next;
        }   
    };
    

    python

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            carry = 0
            res = []
            while l1 or l2 or carry:
                a = b =0
                if l1:
                    a = l1.val
                    l1 = l1.next
                if l2:
                    b = l2.val
                    l2 = l2.next
                temp = a + b + carry
                res.append(temp%10)
                carry = temp // 10
            return res
                
    

    tip:

    循环体中使用的局部变量,每次循环都是使用同一块内存,所以每次都是同一个地址。

  • 相关阅读:
    C++ 纸牌 今日头条面试题
    c++ 病句 今日头条面试题
    C++ 球迷 今日头条面试题
    C++ 活动安排
    C++ 弗洛伊德算法
    填坑 bzoj3337
    bzoj3884 上帝与集合的正确用法
    人参中第一次膜你退货
    洛谷P2216 [HAOI2007]理想的正方形
    洛谷 P1099 树网的核+P2491 [SDOI2011]消防
  • 原文地址:https://www.cnblogs.com/weedboy/p/7143408.html
Copyright © 2011-2022 走看看