Add Two Numbers

Yohan Kim·2021년 10월 3일
0

problem

두 링크드 리스트를 합쳐서 새로운 링크드 리스트를 리턴하는 함수입니다.

solution

//problem no : 2
/**
 * 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) {
        int n = l1->val + l2->val;
        int roundUp = n/10;
        n %= 10;
        
        ListNode* ans = new ListNode(n);
        ListNode* i = ans;
        l1 = l1->next;
        l2 = l2->next;
        
        while(l1 && l2){
            n = l1->val + l2->val + roundUp;
            roundUp = n/10;
            n %= 10;
            i->next = new ListNode(n);
            i = i->next;
            l1 = l1->next;
            l2 = l2->next;
        }
        while(l1){
            n = l1->val + roundUp;
            roundUp = n/10;
            n %= 10;
            i->next = new ListNode(n);
            i = i->next;
            l1 = l1->next;
        }
        while(l2){
            n = l2->val + roundUp;
            roundUp = n/10;
            n %= 10;
            i->next = new ListNode(n);
            i = i->next;
            l2 = l2->next;
        }
        if(roundUp){
            i->next = new ListNode(1);
        }
        return ans;
    }
};

후기

로직은 생각보다 쉽게 구현할 수 있었습니다.
코드가 길어진 이유는 초기값을 계산하여, 불필요한 node를 만들고 싶지않았고, while문이 한번 끝났을때, 이어붙이고 싶었는데,
-9-9-9-9 인경우 때문에 while문이 l1,l2한번 더 돌고 roundUp이 0이 아니면 추가로 노드를 만듭니다.

profile
안녕하세요 반가워요!

0개의 댓글