leetcode

2.两数相加

力扣链接

模拟进位法

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
      ListNode *head = nullptr, *tail = nullptr;
      int carry = 0;
      while (l1 || l2){
        // 求某一位的sum
        int num1 = l1 ? l1->val : 0, num2 = l2 ? l2->val : 0;
        int sum = num1 + num2 + carry;
        // carry 进位
        carry = sum / 10;
        // 确定head 移动tail
        if (!head) {
          head = tail = new ListNode(sum % 10);
        } else {
          tail->next = new ListNode(sum % 10);
          tail = tail->next;
        }
        // 移动l1 l2
        if (l1) l1 = l1->next;
        if (l2) l2 = l2->next;
      }
      if (carry) tail->next = new ListNode(carry);
      return head;
    }
};

问题未解决

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* head = nullptr, *tail = nullptr;
        int carry = 0;
        while (l1 || l2){
            int num1 = l1 ? l1->val:0, num2 = l2 ? l2->val:0;
            int sum = num1 + num2 + carry;
            carry = sum / 10;
            if (!head){
                head = tail = new ListNode(sum % 10);
                // 为什么第一步先移动tail会出问题
                tail = tail->next;
            } else {
                tail = new ListNode(sum % 10);
                tail = tail->next;
            }
            if (l1) l1 = l1->next;
            if (l2) l2 = l2->next;  
        }
        if (carry) tail->next = new ListNode(carry);
        return head;
    }
};

暴力求和数字溢出

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
      if (!l1 && !l2) return nullptr;
      unsigned long long sum = 0, cnt = 0;
      std::vector<unsigned long long> vec1, vec2, vec3;
      while (l1){
        vec1.push_back(l1->val);
        l1 = l1->next;
        cnt++;
      }
      while(l2){
        vec2.push_back(l2->val);
        l2 = l2 ->next;
      }
      for (int i = vec1.size() - 1; i >= 0; i--){
        sum += vec1[i] * pow(10, i);
      }
      for (int i = vec2.size() - 1; i >= 0; i--){
        sum += vec2[i] * pow(10, i);
      }
      while (1){
        vec3.push_back(sum % 10);
        sum /= 10;
        if (sum < 10) break;
      }
      if (sum) vec3.push_back(sum);
      for (int i:vec3) std::cout <<"size= "<< vec3.size() << i << '\n';
      ListNode* head = new ListNode(vec3[0]), *pre = head;
      for (int i = 1; i < vec3.size(); i++){
        ListNode*node = new ListNode(vec3[i]);
        pre->next = node;
        pre = node;
      }
      return head;
    }
};