zoukankan      html  css  js  c++  java
  • 19.1.11 LeetCode 2 Add Two Numbers

    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.
     1 class Solution {
     2 public:
     3     ListNode * addTwoNumbers(ListNode* l1, ListNode* l2) {
     4         int num1, num2;
     5         ListNode*ans,*oldans=NULL,*head;
     6         int inc = 0;
     7         while (l1!= NULL && l2!= NULL) {
     8             num1 = l1->val, num2 = l2->val;
     9             int plus = num1 + num2+inc;
    10             inc = plus / 10;
    11             ans = new ListNode(plus % 10);
    12             if (oldans)
    13                 oldans->next = ans;
    14             else
    15                 head = ans;
    16             oldans = ans;
    17             ans = ans->next;
    18             l1 = l1->next, l2 = l2->next;
    19         }
    20         while (l1 != NULL) {
    21             num1 = l1->val;
    22             int plus = num1 + inc;
    23             inc = plus / 10;
    24             ans = new ListNode(plus % 10);
    25             if (oldans)
    26                 oldans->next = ans;
    27             else
    28                 head = ans;
    29             oldans = ans;
    30             ans = ans->next;
    31             l1 = l1->next;
    32         }
    33         while (l2!= NULL) {
    34             num1 = l2->val;
    35             int plus = num1 + inc;
    36             inc = plus / 10;
    37             ans = new ListNode(plus % 10);
    38             if (oldans)
    39                 oldans->next = ans;
    40             else
    41                 head = ans;
    42             oldans = ans;
    43             ans = ans->next;
    44             l2 = l2->next;
    45         }
    46         if (inc > 0) {
    47             ans = new ListNode(inc);
    48             if (oldans)
    49                 oldans->next = ans;
    50             else
    51                 head = ans;
    52         }
    53         return head;
    54     }
    55 };
    View Code

    普通地做了下模拟,是不是有点太麻烦了呢?

    注定失败的战争,也要拼尽全力去打赢它; 就算输,也要输得足够漂亮。
  • 相关阅读:
    ServletContext笔记
    Session笔记
    Cookie笔记
    递归实现取数组最大值
    栈结构实现队列结构
    返回栈中最小元素的两种实现O(1)
    数组实现不超过固定大小的队列(环形数组)
    双向链表实现栈和队列
    Windows Server 2008 R2 / Windows Server 2012 R2 安装 .NET Core 3.1
    Windows 7 / Windows Server 2008 R2 升级至 SP1
  • 原文地址:https://www.cnblogs.com/yalphait/p/10255027.html
Copyright © 2011-2022 走看看