A 40ms C++ Solution


  • 0
    Y
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            long num1 = 0, num2 = 0, count = 0, sum = 0;
            vector<int> nums;
            while(l1) {
                num1 = num1 + l1->val*pow(10,count);
                l1 = l1->next;
                count++;
            }
            count = 0;
            while(l2) {
                num2 = num2 + l2->val*pow(10,count);
                l2 = l2->next;
                count++;
            }
            sum = num1 + num2;
            ListNode *ans = new ListNode(sum%10);
            ListNode *cur = ans;
            sum = sum / 10;
            while(sum) {
                cur->next = new ListNode(sum%10);
                cur = cur->next;
                sum /= 10;
            }
            return ans;
        }
    };

  • 0

    Is there any possibility that num1, num2 and sum beyond the upper bound of int?


  • 0
    Y

    Yeah, it maybe. It seems in OJ, "long" is longer than "int" as it shown error when I use "int". We can use long long int if necessary.


  • 0

    maybe maybe maybe be e .....


Log in to reply
 

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