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

    注意点:改了又改,好多测试用例没有考虑到。代码很乱~

          1.{5},{5}->{0,1}

          2.{1},{9,9}->{0,0,1}

          3.{9,8},{1}->{0,9}

    class Solution {
    public:
    	int Length(ListNode *l)
    	{
    		int len=0;
    		while(l)
    		{
    			l=l->next;
    			len++;
    		}
    		return len;
    	}
    	ListNode *func(ListNode *l1,ListNode *l2)
    	{
    		ListNode *p=l1;
    		ListNode *q=l2;
    		ListNode *r=p;
    		bool flag=false;
    		while(q)
    		{
    			r=p;
    			if(flag)
    			{
    				p->val+=q->val+1;
    				flag=false;
    			}
    			else
    				p->val+=q->val;
    			if(p->val>9)
    			{
    				flag=true;
    				p->val=p->val%10;
    			}
    			p=p->next;
    			q=q->next;
    		}
    		while(flag)
    		{
    			if(!p)
    			{
    				ListNode *newnode=new ListNode(1);
    				r->next=newnode;
    				flag=false;
    			}
    			else
    			{
    				p->val+=1;
    				flag=false;
    				if(p->val>9)
    				{
    					flag=true;
    					p->val=p->val%10;
    					r=p;
    					p=p->next;
    				}
    			}
    		}
    		return l1;
    	}
        ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
    		int len1=Length(l1);
    		int len2=Length(l2);
    		if(len1==0) return l2;
    		else if (len2==0) return l1;
    		else if(len1<len2) return func(l2,l1);
    		else return func(l1,l2);
        }
    };
    

      

  • 相关阅读:
    云计算
    uc/xi
    互联网 2.0概念
    java连接数据库
    记录一下安装 mysql 的踩坑之路
    1
    Linux介绍与基本必知命令
    Web课程Linux命令统计
    7——条件判断、三目运算、条件循环、迭代循环
    6——散列类型、运算符优先级、逻辑运算
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3410215.html
Copyright © 2011-2022 走看看