• [Leetcode 40] 1 Add Two Numbers


    Problem:

    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

    Analysis:

    Simple digit addition, pay attention to carry.

    To save space here, we try to merge l2 into l1. This allow us implement a in-place solution.

    Code:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
    12         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         if (l1 == NULL) return l2;
    15         if (l2 == NULL) return l1;
    16         
    17         int carry = 0;
    18         ListNode *dummy = new ListNode(0);
    19         dummy->next = l1;
    20         while ((dummy->next != NULL) && (l2 != NULL)) {
    21             dummy = dummy->next;
    22             int sum = dummy->val + l2->val + carry;
    23             dummy->val = sum%10;
    24             carry = sum / 10;
    25             
    26             l2 = l2->next;
    27         }
    28         
    29         if (l2 != NULL)
    30             dummy->next = l2;
    31         
    32         while (dummy->next != NULL) {
    33             dummy = dummy->next;
    34             if (carry != 0) {
    35                 int sum = dummy->val + carry;
    36                 dummy->val = sum % 10;
    37                 carry = sum /10;
    38             } else {
    39                 break;   
    40             }
    41         }
    42 
    43         if (carry == 1)
    44             dummy->next = new ListNode(1);
    45         
    46         return l1;
    47     }
    48 };
    View Code
  • 相关阅读:
    django1.8升级1.9的几个问题
    App免费推广途径概要
    Django Channels 入门指南
    小谈业务应用架构
    比技术债更可怕的人债
    js数据结构与算法--递归
    常见react面试题汇总
    如何使用koa实现socket.io官网的例子
    Vue插槽
    10分钟了解 react 引入的 Hooks
  • 原文地址:https://www.cnblogs.com/freeneng/p/3096323.html
Copyright © 2020-2023  润新知