๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš“ Self Study/๐Ÿ”“ LeetCode

LeetCode (Add two numbers) C++

by UKHYUN22 2022. 1. 7.
728x90

 

 

ํ‘œํ˜„ ๋ฒ”์œ„๋ฅผ ๋„˜์–ด๊ฐ€๋Š” ์ˆซ์ž๊ฐ€ ์žˆ์–ด์„œ ํ•œ ๋น„ํŠธ์”ฉ ์—ฐ์‚ฐ์„ ํ•ด์ค˜์•ผ ํ–ˆ๋˜ ๋ฌธ์ œ. long long์œผ๋กœ ํ•ด๋„ ์ฒ˜๋ฆฌ๊ฐ€ ์•ˆ๋๋‹ค.

 

/**
 * 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) {
        
        string list = "";
        int carry = 0;
        
        while(l1 != NULL || l2 != NULL) {
            int sum = 0;
            
            if(l1 != NULL && l2 != NULL)
                sum = l1->val + l2->val + carry;
            else if(l1 == NULL && l2 != NULL)
                sum = l2->val + carry;
            else if(l1 != NULL && l2 == NULL)
                sum = l1->val + carry;
                        
            if(sum >= 10){
                carry = 1;
                sum = sum % 10;
            } else {
                carry = 0;
            }
            
            list = list + to_string(sum);
            
            if(l1 != NULL)
                l1 = l1->next;
            if(l2 != NULL)
                l2 = l2->next;
        }
        
        if(carry == 1) {
            list = list + "1";
        }
        
        ListNode* head = new ListNode();
        ListNode* answer = head;
        
        for(int i = 0 ; i < list.size() ; i++) {
            answer->next = new ListNode();
            answer = answer->next;
            answer->val = list[i] - '0';
        }
        
        return head->next;   
    }
};

 

'๐Ÿš“ Self Study > ๐Ÿ”“ LeetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode (Two Sum) C++  (0) 2022.01.07
LeetCode (Employee Importance) C++  (0) 2022.01.06
LeetCode (Sum of Left Leaves) C++  (0) 2022.01.06