• leetcode--Add Two Numbers


    1.题目描述

    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

    2.解法分析

    题目很简单,不用描述了。

    /**
     * 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
            
            ListNode *cur1=l1;
            ListNode *cur2=l2;
            int carrier=0;
            int curDigit=0;
            ListNode *head;
            int flag = 0;
            ListNode *prev;
            while(cur1!=NULL&&cur2!=NULL)
            {
                curDigit=(cur1->val+cur2->val+carrier)%10;
                carrier=(cur1->val+cur2->val+carrier)/10;
                ListNode *cur=new ListNode(curDigit);
                
                if(flag==0)
                {
                    head=cur;
                    prev=cur;
                    flag =1;
                }
                else
                {
                    prev->next=cur;
                    prev=cur;
                }
                
                cur1=cur1->next;
                cur2=cur2->next;
            }
     
            if(cur1!=NULL||cur2!=NULL)
            {
                cur1=cur1!=NULL?cur1:cur2;
            
                while(cur1!=NULL)
                {
                    curDigit=(cur1->val+carrier)%10;
                    carrier=(cur1->val+carrier)/10;
                    ListNode *cur=new ListNode(curDigit);
                    prev->next=cur;
                    prev=cur;
                    cur1=cur1->next;
                }
            }
            
            if(carrier!=0)
            {
                ListNode *cur=new ListNode(carrier);
                prev->next=cur;
            }
            
            return head;
        }
    };
  • 相关阅读:
    架构之道(5)
    项目的命名规范
    semantic框架
    jquery.timepicker.js
    jquery.marquee.js
    CkEditor
    快速测试,其实没什麽大不了
    架构之道(4)
    架构之道(3)
    子网划分与子网掩码
  • 原文地址:https://www.cnblogs.com/obama/p/3267081.html
Copyright © 2020-2023  润新知