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);
        }
    };
    

      

  • 相关阅读:
    CF1454F Array Partition
    leetcode1883 准时抵达会议现场的最小跳过休息次数
    leetcode1871 跳跃游戏 VII
    leetcode1872 石子游戏VIII
    CF1355C Count Triangles
    CF1245D Shichikuji and Power Grid
    CF1368C Even Picture
    CF1368D AND, OR and square sum
    CF1395C Boboniu and Bit Operations
    SpringBoot和开发热部署
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3410215.html
Copyright © 2011-2022 走看看