zoukankan      html  css  js  c++  java
  • 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.

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8

    把较短的字符串的数字加到较长的字符串上,唯一注意的是进位问题

    c++代码

     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         ListNode *p = l1;
    13         ListNode *q = l2;
    14         
    15         int len1 = 0;
    16         int len2 = 0;
    17         
    18         while(p != nullptr)
    19         {
    20             ++ len1;
    21             p = p -> next;
    22         }
    23         
    24         while(q != nullptr)
    25         {
    26             ++ len2;
    27             q = q -> next;
    28         }
    29         
    30         ListNode *res = nullptr;
    31         
    32         if(len1 >= len2)
    33         {
    34             res = l1;
    35             p = l1;
    36             q = l2;
    37         }
    38         else 
    39         {
    40             res = l2;
    41             p = l2;
    42             q = l1;
    43         }
    44         
    45         while(q != nullptr)
    46         {
    47             p -> val += q -> val;
    48             p = p -> next;
    49             q = q -> next;
    50         }
    51         
    52         ListNode *r = res;
    53         
    54         while(r -> next != nullptr)
    55         {
    56             if(r -> val >= 10)
    57             {
    58                 int t = r -> val / 10;
    59                 r -> val = r -> val % 10;
    60                 r -> next -> val += t;
    61             }
    62                 
    63             r = r -> next;
    64         }
    65         
    66         if(r -> val >= 10)
    67         {
    68             int t = r -> val / 10;
    69             r -> val %= 10;
    70             ListNode *tmp = new ListNode(t);
    71             r -> next = tmp;
    72         }
    73         return res;
    74     }
    75 };
  • 相关阅读:
    virtualenv建立新的python环境
    c++ 类构造函数&析构函数
    Spring中的BeanPostProcessor和BeanFactoryPostProcessor
    01 | 日志段:保存消息文件的对象是怎么实现的?
    linux 常用命令大全
    select/poll/epoll
    Redis 数据结构 api操作复杂度 ~~~~
    Redis底层数据结构----1 结构与命令
    Linux进阶系列 1 --- 进程通信
    让我们来写个算法吧,(6);链表排序
  • 原文地址:https://www.cnblogs.com/xjtuchenpeng/p/7724024.html
Copyright © 2011-2022 走看看