본문 바로가기
Algorithm things

[LeetCode] Add Two Numbers

by Warehaus 2021. 3. 21.

코드가 좀 길지않나 싶다.

줄이기는 또 귀찮고..

 

문제를 제대로 안읽고 그냥 다 더해서 리스트를 만들라는건가 싶었는데

node 개수가 1~100 개라고 하니 그것은 아닌 것 같고, Node를 방문하면서 계속 만들어 내야할 것 같았다.

 

한 노드에 저장되는 수는 0~9 이기에 Carry 는 1이상 나오지 않는다고 생각했다.

 

Constraints:

  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        
        auto carry = 0;
        
        ListNode* l3 = nullptr; // l3 first
        ListNode* l3_cur = nullptr; // l3 cursor
        
        while ( 1 )
        {
            int v = l1->val + l2->val + carry;
            
            if ( v >= 10 )
            {
                v %= 10;
                carry = 1;
            }
            else if ( carry != 0 )
            {
                carry = 0;
            }
            
            if ( l3 == nullptr )
            {
                l3 = new ListNode(v);
                l3_cur = l3;
            }
            else
            {
                ListNode* newNode = new ListNode(v);                
                l3_cur->next = newNode;
                l3_cur = newNode;                
            }
            
            if ( l1->next == nullptr && l2->next == nullptr )
            {
                if ( carry != 0 )
                {
                    ListNode* nN = new ListNode(carry);
                    l3_cur->next = nN;
                    l3_cur = nN;
                }
                break;            
            }
            
            // Move to next node.
            if ( l1->next == nullptr )
            {
                // The next round will be for l2. Set l1 value to zero which is used already.
                l1->val = 0;
                l2 = l2->next;
            }
            else if ( l2->next == nullptr )
            {
                l2->val = 0;
                l1 = l1->next;
            }
            else
            {
                l1 = l1->next;
                l2 = l2->next;
            }                            
        }
        
        
        
        return l3;        
    }
};

 

'Algorithm things' 카테고리의 다른 글

[LeetCode] Weekly Contest 234  (0) 2021.03.27
[LeetCode] 62. Unique Paths  (0) 2021.03.27
[LeetCode] 6. ZigZag Conversion  (0) 2021.03.26
[LeetCode] 5. Longest Palindromic Substring  (0) 2021.03.25
[LeetCode] Two sum  (0) 2021.03.21