2. Add Two Numbers(中等)

/**
 * 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* first = l1;
        ListNode* second = l2;
        int result1=0,result2=0;
        long long result=0;
        stack<int> S;
        int count=0;
        
        while(l1 != NULL){
            S.push(l1->val);
            l1 = l1->next;
        }
            
            
        count = S.size()-1;
        while(!S.empty()){
            result1 += pow(10,count--) * S.top();
            S.pop();
        }
            
        
        while(l2 != NULL){
            S.push(l2->val);
            l2 = l2->next;
        }
            
        count = S.size()-1;
        while(!S.empty()){
            result2 += pow(10,count--) * S.top();
            S.pop();
        }
            
        result = result1 + result2;
        delete first,second;
        
        // ListNode*p = new ListNode(-1);  //头节点
        ListNode* pHead = NULL;
        ListNode* p = pHead;
        
        if(!result){
            ListNode* q = new ListNode(0);
            pHead = q;
        }
        while(result){
            int val = result % 10;
            result /= 10;
            
            ListNode* q = new ListNode(val);
            if(pHead == NULL){
                pHead = q;
                p = q;
            }
            else{
                p->next = q;
                p = p->next;
            }
        }
        return pHead;
    }
};
此方法会溢出,超过long long 型范围

相关文章:

  • 2022-01-29
  • 2021-10-28
  • 2021-08-23
  • 2021-10-13
  • 2021-11-07
  • 2021-05-18
  • 2022-01-04
  • 2022-01-14
猜你喜欢
  • 2021-04-01
  • 2021-09-07
  • 2021-09-02
  • 2021-06-02
  • 2022-03-03
  • 2021-07-17
  • 2021-09-28
相关资源
相似解决方案