알고리즘/LeetCode
LeetCode - 2. Add Two Numbers
시나모온
2021. 10. 12. 00:15
문제 링크입니다 : https://leetcode.com/problems/add-two-numbers/
Add Two Numbers - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
C++
/**
* 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 sum = l1->val + l2->val;
ListNode* head = new ListNode(sum % 10);
ListNode* tail = head;
bool carry = sum / 10;
l1 = l1->next;
l2 = l2->next;
while (l1 || l2 || carry) {
if (l1 == nullptr && l2 == nullptr) {
sum = carry;
} else if (l1 == nullptr) {
sum = l2->val + carry;
l2 = l2->next;
} else if (l2 == nullptr) {
sum = l1->val + carry;
l1 = l1->next;
} else {
sum = l1->val + l2->val + carry;
l1 = l1->next;
l2 = l2->next;
}
tail->next = new ListNode(sum % 10);
carry = sum / 10;
tail = tail->next;
}
return head;
}
};
JAVA
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int sum = l1.val + l2.val;
ListNode head = new ListNode(sum % 10);
ListNode tail = head;
int carry = sum >= 10 ? 1 : 0;
l1 = l1.next;
l2 = l2.next;
while(l1 != null || l2 != null) {
if (l1 == null && l2 == null) {
sum = carry;
} else if (l1 == null) {
sum = l2.val + carry;
l2 = l2.next;
} else if (l2 == null) {
sum = l1.val + carry;
l1 = l1.next;
} else {
sum = l1.val + l2.val + carry;
l1 = l1.next;
l2 = l2.next;
}
tail.next = new ListNode(sum % 10);
carry = sum >= 10 ? 1 : 0;
tail = tail.next;
}
if (carry == 1) {
tail.next = new ListNode(1);
}
return head;
}
}
Python3
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
list1, list2 = l1, l2
sum_val = list1.val + list2.val
carry = 1 if sum_val >= 10 else 0
head = ListNode(sum_val % 10)
tail = head
list1 = list1.next
list2 = list2.next
while list1 or list2 :
if list1 and list2:
sum_val = list1.val + list2.val + carry
list1 = list1.next
list2 = list2.next
elif list1 == None:
sum_val = list2.val + carry
list2 = list2.next
else:
sum_val = list1.val + carry
list1 = list1.next
tail.next = ListNode(sum_val % 10)
tail = tail.next
carry = 1 if sum_val >= 10 else 0
if carry != 0:
tail.next = ListNode(1)
return head
개발 환경 : vscode
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~