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


    就是简单的高精度加法,刚开始理解错题意WA了好几次。

    要注意的是:

    判断两个list有没有都算到头;

    判断进位是否为0;

    考虑有没有多申请节点,最后一个节点不能为0。


    以下是我的代码:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* re = new ListNode(0);
            ListNode* result = re;
            int carry = 0;
            while (l1 || l2 || carry) {
                int tmp = (l1?(l1->val):0) + (l2?(l2->val):0) + carry;
                re->val = tmp % 10;
                carry = tmp / 10;
                if (l1) l1 = l1->next;
                if (l2) l2 = l2->next;
                if (l1 || l2 || carry) re->next = new ListNode(0), re = re->next;
            }
            return result;
        }
    };
  • 相关阅读:
    转:ORA-12541:TNS:无监听程序问题
    实战jmeter入门压测接口性能
    数据库的4种常用设计模式
    三范式,数据库设计的基本准则
    html5学习2
    html5学习1
    php初写成
    Typora编辑区域空白过大问题
    CURL 常用命令
    阿里云镜像创建Spring Boot工厂
  • 原文地址:https://www.cnblogs.com/zmj97/p/7526183.html
Copyright © 2011-2022 走看看