zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    AngularJS(3)-过滤器
    AngularJS(2)-Scope作用域和控制器
    iOS局部刷新
    python(一)入门
    Java基础
    AngularJS(1)随笔
    mac下如何查看指定端口被谁占用并且杀死该进程
    Python 字节码bytecode
    Python 作用域和命名空间
    Python函数的默认参数的设计【原创】
  • 原文地址:https://www.cnblogs.com/obama/p/3267081.html
Copyright © 2011-2022 走看看