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 }
  • 相关阅读:
    BZOJ 3677 连珠线
    BZOJ 3676 回文串
    BZOJ 3675 序列分割
    BZOJ 4013 实验比较
    BZOJ 4011 落忆枫音
    使用Google BBR加速 VPS
    OSX编译安装Python3及虚拟开发环境Virtualenv
    OSX安装Mysql8.0
    OpenSSL编程之摘要
    OpenCA搭建
  • 原文地址:https://www.cnblogs.com/wei-li/p/AddTwoNumbers.html
Copyright © 2011-2022 走看看