Why my code is wrong?(Add Two Numbers)


  • 0
    Z

    /////////////////////////////////////////////////我的代码

    /**

    • 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)
    {
    ListNode *p1,*p2;
    p1=l1;
    p2=l2;
    int r1=0;
    int r2=0;

        //data 1
        for(int i=0;p1!=NULL;i++)
        {
            r1+=(p1->val)*pow(10,i);
            p1=p1->next;
        }
        
        //data 2
        for(int i=0;p2!=NULL;i++)
        {
            r2+=(p2->val)*pow(10,i);
            p2=p2->next;
        }
        
        //save the sum o
        int c=r1+r2;
        
        ListNode *phead=(ListNode*)malloc(sizeof(ListNode));
        phead->next=NULL;
        ListNode *p3=phead;
        do
        {
            ListNode *ptemp=(ListNode*)malloc(sizeof(ListNode));
            ptemp->val=c%10;
            p3->next=ptemp;
            p3=ptemp;
            c=c/10;
        }while((c)!=0);
        p3=NULL;
        return phead->next;
        
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.