What is the mistake,please tell me(the code is ugly but just tell why it can not be accepted)


  • 0
    K
    class Solution {
    public:
        ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
            int i=1;
            int k1=0,k2=0,k3=0;
            ListNode *l3,*pointer;
            while(l1->next!=NULL){
                l1=l1->next;
                k1=(l1->val)*i+k1;
                i*=10;
            }
            i=1;
            while(l2->next!=NULL){
                l2=l2->next;
                k2=(l2->val)*i+k2;
                i*=10;
            }
            if(k1==0) return l2;
            if(k2==0) return l1;
            k3=k1+k2;
            pointer=l3;
            while(k3!=0){
                pointer=new ListNode(k3%10);
                pointer=pointer->next;
                k3/=10;
            }
            return l3;
        }
    };

  • 0
    N

    int overflow. you cant convert them to ints and add as it tries with very big numbers that do not fit in an int type.


  • 0
    W

    Just as @ nbauerlevey has said, you can't convert each list into integers and add two numbers. If the integers is very big, the k1 and k2 will be overflow, or k1 + k2. You may think using long long instead int, but its not a good way to solve this question. For this problem, we should scanning two lists and doing sum operations each node.


  • 0
    C

    The numbers being reversed (LSB to MSB in the list) provides you the hint that you need to operate at each pair of digits from each number, moving forward the carry. Transforming the domain of representation is never meant for this type of questions.


Log in to reply
 

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