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

    You are given two linked lists representing two non-negative numbers. 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.

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

    模拟加法,注意最后加法结束时可能有进位需要处理一下。

    /**
     * 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) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if (l1 == NULL && l2 == NULL)
                return NULL;
                
            ListNode *head = NULL;
            ListNode *pre = NULL;
            int flag = 0;
            
            while(l1 && l2)
            {
                ListNode *node = new ListNode(l1->val + l2->val + flag);
                flag = node->val / 10;
                node->val %= 10;
                
                if (head == NULL)
                    head = node;
                else
                    pre->next = node;
                    
                pre = node;
                
                l1 = l1->next;
                l2 = l2->next;
            }
            
            while(l1)
            {
                ListNode *node = new ListNode(l1->val + flag);
                flag = node->val / 10;
                node->val %= 10;
                
                if (head == NULL)
                    head = node;
                else
                    pre->next = node;
                    
                pre = node;
                
                l1 = l1->next;
            }
            
            while(l2)
            {
                ListNode *node = new ListNode(l2->val + flag);
                flag = node->val / 10;
                node->val %= 10;
                
                if (head == NULL)
                    head = node;
                else
                    pre->next = node;
                    
                pre = node;
                
                l2 = l2->next;
            }
            
            if (flag > 0)
            {
                ListNode *node = new ListNode(flag);
                pre->next = node;
            }
            
            return head;
        }
    };
  • 相关阅读:
    操作技巧——电脑远程控制
    软件安装——internal error2503/2502
    系统常识——虚拟内存地址
    操作技巧——保障无线上网的技巧
    操作技巧——输入法转换问题
    软件安装——彻底卸载MySQL
    Java——this
    python百度贴吧爬虫
    糗事百科python爬虫
    python请求带cookie
  • 原文地址:https://www.cnblogs.com/chkkch/p/2742723.html
Copyright © 2011-2022 走看看