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

    Description: 

    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.

    描述:

     给定两个非空链表,分别表示两个非负整数。整数的组成数字按照逆序排列,并且链表的每个节点表示一个数字。将两个整数相加,并以链表的形式返回相加和。

    假设两个整数均不包含前导0(除了整数0本身)。

    例子:

    输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
    输出:7 -> 0 -> 8
    解释: 342 + 465 = 807

    遍历两个数字,并逐节点相加。以变量carrier表示进位。

    /**
     * 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 *p1 = l1;
            ListNode *p2 = l2;
            int carrier = 0;
            ListNode *l3 = NULL;
            ListNode *p = NULL;
            
            while(p1 != NULL || p2 != NULL) {
                int val1 = p1 == NULL ? 0 : p1->val;
                int val2 = p2 == NULL ? 0 : p2->val;
                p1 = p1 == NULL ? NULL : p1->next;
                p2 = p2 == NULL ? NULL : p2->next;
                
                int val = val1 + val2 + carrier;
                carrier = val >= 10 ? 1 : 0;
                val = val >= 10 ? val - 10 : val;
                ListNode *node = new ListNode(val);
                if(l3 == NULL) {
                    l3 = p = node;
                } else {
                    p->next = node;
                    p = node;
                }
            }
            if(carrier) {
                ListNode *node = new ListNode(carrier);
                p->next = node;
            }
            return l3;
        }
    };
    

      

    时间复杂度为O(max(n1, n2)), 空间复杂度为O(max(n1, n2) + 1)。

  • 相关阅读:
    php ajax分页的例子,在使用中
    PHP远程文件管理,可以给表格排序,遍历目录,时间排序
    背景变暗的div可拖动提示窗口,兼容IE、Firefox、Opera
    CSS简洁的左侧菜单(侧拉菜单,向右显示)
    无间断循环滚动(兼容IE、FF)
    poj 1007 求逆序数
    poj 1775 简单搜索
    面向对象之继承和组合浅谈
    在flex中导入fl包
    C99中包括的特性
  • 原文地址:https://www.cnblogs.com/alpaca/p/9469893.html
Copyright © 2011-2022 走看看