• [LeetCode] 2. Add Two Numbers

    2022. 1. 15.

    by. ํ•ด๋Š”์„ 

    ์‰ฝ๊ฒŒ ๋งํ•˜๋ฉด ์ˆซ์ž๋ฅผ ๋’ค์ง‘์–ด์„œ 1์˜์ž๋ฆฌ๋ถ€ํ„ฐ ๋งž์ถฐ์„œ ๋„ฃ์–ด์ฃผ๋Š” ๋ง์…ˆ์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค. 

    ์ด๋ฒˆ์—๋Š” ์ •๋ง ๋ฌด์ง€์„ฑ์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์งœ์„œ ์กฐ๊ฑด๋ฌธ์ด ๋”๋Ÿฝ๊ฒŒ ๋“ค์–ด๊ฐ”๋Š”๋ฐ, ์ข€ ๋” ๊น”๋”ํ•˜๊ฒŒ ํ•ด์ฃผ๋ ค๋ฉด ์ € ์กฐ๊ฑด๋“ค์„ while๋ฌธ์˜ ์กฐ๊ฑด์„ ๊ฑธ์–ด์ฃผ๋ฉด ๋œ๋‹ค.

     

    /**
     * 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) {
            
            ListNode* result = NULL;
            ListNode* result_pointer = NULL;
            int up = 0;
            
            while(true){
                ListNode* temp = new ListNode();
                temp -> next = NULL;
                
                int val = up;
                up = 0; 
    
                if (l1 != NULL) val += l1->val;
                if (l2 != NULL) val += l2->val;
    
                if(val >= 10){
                    val -= 10;
                    up = 1;
                }
    
                temp -> val = val;
                    
                if (result_pointer == NULL) {
                    result = temp;
                    result_pointer = result;
                }
                else {
                    result_pointer->next = temp;
                    result_pointer = result_pointer->next;
                }
                
                if (l1 != NULL && l1->next != NULL) l1 = l1->next;
                else l1 = NULL;
                
                if (l2 != NULL && l2->next != NULL) l2 = l2->next;
                else l2 = NULL;
                
                if (l1 == NULL && l2 == NULL && up == 0) break;
            }
            return result;
        }
    };

     

    '๐Ÿ“šSTUDY > ๐Ÿ‘€ coding test๋Œ€๋น„' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

    [LeetCode] 59. Spiral Matrix II  (0) 2022.01.15
    [LeetCode] 328. Odd Even Linked List  (0) 2022.01.15
    [๋ฐฑ์ค€] 1158๋ฒˆ ์š”์„ธํ‘ธ์Šค ๋ฌธ์ œ  (0) 2020.02.08

    ๋Œ“๊ธ€