zoukankan      html  css  js  c++  java
  • Leetcode2.Add Two Numbers两数相加

    给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

    你可以假设除了数字 0 之外,这两个数字都不会以零开头。

    示例:

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

    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
        {
            int x = 0;
            ListNode* head = NULL;
            ListNode* last = NULL;
            while(l1 && l2)
            {
                int temp = l1 ->val + l2 ->val + x;
                x = temp / 10;
                temp = temp % 10;
                if(head == NULL)
                {
                    head = new ListNode(temp);
                    last = head;
                }
                else
                {
                    last ->next = new ListNode(temp);
                    last = last ->next;
                }
                l1 = l1 ->next;
                l2 = l2 ->next;
            }
            while(l1)
            {
                int temp = l1 ->val + x;
                x = temp / 10;
                temp = temp % 10;
                if(head == NULL)
                {
                    head = new ListNode(temp);
                    last = head;
                }
                else
                {
                    last ->next = new ListNode(temp);
                    last = last ->next;
                }
                l1 = l1 ->next;
            }
            while(l2)
            {
                int temp = l2 ->val + x;
                x = temp / 10;
                temp = temp % 10;
                if(head == NULL)
                {
                    head = new ListNode(temp);
                    last = head;
                }
                else
                {
                    last ->next = new ListNode(temp);
                    last = last ->next;
                }
                l2 = l2 ->next;
            }
            if(x != 0)
            {
                last ->next = new ListNode(x);
                last = last ->next;
            }
            return head;
        }
    };
  • 相关阅读:
    python之字典
    Python包管理工具
    【转】Python实现修改Windows CMD命令行输出颜色(完全解析)
    进程池中传递实例方法问题
    HTML协议详解
    【转】python数据格式化之pprint
    【转】Python装饰器与面向切面编程
    【转】TCP/IP报文格式
    python之线程学习
    python之面向对象
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433904.html
Copyright © 2011-2022 走看看