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;
        }
    };
  • 相关阅读:
    说说JSON和JSONP,也许你会豁然开朗,含jQuery用例
    利用CSS3实现页面淡入动画特效
    ajax
    jQuery弹性滑动导航菜单实现思路及代码
    angular 管理后台
    jq简单选项卡
    按钮60秒倒计时
    jq倒计时
    angular ui-route
    flex弹性布局
  • 原文地址:https://www.cnblogs.com/zmj97/p/7526183.html
Copyright © 2011-2022 走看看