• LeetCode OJ


    题目:

    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

    解题思路:

    直接一个个的加就行了,注意进位和边界处理。

    代码:

     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         if (l1 == NULL) return l2;
    13         if (l2 == NULL) return l1;
    14         
    15         ListNode* head = new ListNode((l1->val + l2->val) % 10);
    16         int carry = (l1->val + l2->val) / 10;
    17         ListNode* p1 = l1->next, *p2 = l2->next;
    18         
    19         ListNode* cur = head;
    20         while (p1 != NULL && p2 != NULL) {
    21             int tmp = p1->val + p2->val + carry;
    22             cur->next = new ListNode(tmp % 10);
    23             carry = tmp / 10;
    24             p1 = p1->next;
    25             p2 = p2->next;
    26             cur = cur->next;
    27         }
    28         while (p1 != NULL) {
    29             int tmp = p1->val + 0 + carry;
    30             cur->next = new ListNode(tmp % 10);
    31             carry = tmp / 10;
    32             p1 = p1->next;
    33             cur = cur->next;
    34         }
    35         while (p2 != NULL) {
    36             int tmp = p2->val + 0 + carry;
    37             cur->next = new ListNode(tmp % 10);
    38             carry = tmp / 10;
    39             p2 = p2->next;
    40             cur = cur->next;
    41         }
    42         if (carry) {
    43             cur->next = new ListNode(carry);
    44         }
    45         return head;
    46     }
    47 };
  • 相关阅读:
    第2章 NIO入门
    Docker Compose命令详解
    网络层相关术语解释
    linux查看并发连接数
    带宽计算方法
    ELK日志分析平台搭建
    mysql查找json格式列的指定字段值
    Oracle性能优化
    修改hosts文件不需要重启的方法
    freeswitch的internal的profile无法启动
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3810827.html
Copyright © 2020-2023  润新知