zoukankan      html  css  js  c++  java
  • 【题解】【链表】【Leetcode】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

    思路:乍一看以为是大整数,实则相当简单,比Add Binary还要简单

    代码:

     1 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
     2     return addTwoDigit(l1,l2,0);
     3 }
     4 ListNode *addTwoDigit(ListNode *d1, ListNode *d2, int carry){
     5     int sum = carry;
     6     ListNode *n1 = d1, *n2 = d2;//不要轻易修改输入参数, 尤其是链表问题中
     7     if(d1 != NULL){
     8         sum += d1->val;
     9         n1 = d1->next;
    10     }
    11     if(d2 != NULL){
    12         sum += d2->val;
    13         n2 = d2->next;
    14     }
    15     ListNode *newNode = new ListNode(sum%10);
    16     
    17     if(d1 == NULL && d2 == NULL){
    18         if(sum == 0)
    19             return NULL;//Avoid test case:{0}, {0} => {0,0}
    20         return newNode;
    21     }
    22     
    23     ListNode *nextNode = addTwoDigit(n1, n2, sum/10);
    24     newNode->next = nextNode;
    25     return newNode;
    26 }
  • 相关阅读:
    23)PHP,数组操作函数
    22)PHP,数组排序函数
    21)PHP,杨辉三角
    数据库三大范式
    SQL Server 中关于EXCEPT和INTERSECT的用法
    面试准备
    面试总结
    jQuery函数attr()和prop()的区别
    SVN checkout出某个特定版本
    SVN 中的忽略文件
  • 原文地址:https://www.cnblogs.com/wei-li/p/AddTwoNumbers.html
Copyright © 2011-2022 走看看