본문 바로가기
🚓 Self Study/🔓 LeetCode

LeetCode (Add two numbers) C++

by H_uuuk 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