• 2. Add Two Numbers[M]两数相加


    题目


    You are given two non-empty linked lists representing two non-negative integers. 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.
    You may assume the two numbers do not contain any leading zero, except the number 0 itself.
    Example:
     Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
     Output: 7 -> 0 -> 8
     Explanation: 342 + 465 = 807.

    思路


    主要是考察链表的求和,由于链表中存放的是逆序的数字,所以两个数的个位数已经对齐,不用考虑对齐问题。其次要考虑到进位的问题:

    • 当前位数字:sum %10
    • 进位:sum / 10

    C++

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            
        ListNode* result = new ListNode(-1);
        ListNode* aux = result; //辅助,用来处理中间链表
        int carry = 0;
        while(l1 != nullptr || l2 != nullptr || carry != 0){ 
            
            //这种方法使得当其中一个链表为空时,也能作加法,从而能够同时对两个链表进行循环
            int a = l1 ? l1->val : 0; //判断链表当前是否为空,如果为空,则值为0
            int b = l2 ? l2->val : 0;
    
            int sum = a + b + carry;
            carry = sum / 10; //进位用取模来获得
            aux->next = new ListNode(sum%10); //通过取模消除进位的影响
            aux = aux ->next;
            if(l1 != nullptr )
                l1 = l1->next;
            if(l2 != nullptr )
                l2 = l2->next;
        }
                 
        return result->next;
    }
    

    Python

    def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            result = ListNode(-1)
            aux = result
            carry = 0  
            while(l1 or l2 or carry):
                a = l1 and l1.val or 0
                b = l2 and l2.val or 0
                sum = a + b + carry
                carry = sum / 10
                aux.next = ListNode (sum % 10)
                aux = aux.next
                if(l1):
                    l1 = l1.next
                if(l2):
                    l2 = l2.next
                    
            return result.next
    
  • 相关阅读:
    网友心得 说说.NET中的反射(转帖)
    javascript的函数(转)
    asp.net基于窗体的身份验证
    创建ASP.NET WEB自定义控件(转)
    .net调用Oracle存储过程
    写字间里程序员
    世界四大杀毒软件调侃
    技巧/诀窍:在ASP.NET中重写URL(转)
    VS2008中JavaScript编辑调试器的秘密
    如何用C#语言构造蜘蛛程序
  • 原文地址:https://www.cnblogs.com/Jessey-Ge/p/10943980.html
Copyright © 2020-2023  润新知