[Leetcode] 2. Add Two Numbers
2024. 2. 26. 23:17ㆍTech: Algorithm
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Constraints:
- The number of nodes in each linked list is in the range [1, 100].
- 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros
Solution 1.
l1, l2 순서대로 앞에서부터 보면서 더하되, 더한 값이 10보다 크면 1의 자리로 ListNode 추가, 그 이후에 다음 더한 값에 num값과 같이 더해주면 되는데 이때 num을 보통 carry 변수라고 쓰는 것이 더 좋음.
/**
* 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* ret = new ListNode(0);
ListNode* tail = ret;
int num=0, sum=0;
while(l1!=nullptr || l2!=nullptr || num!=0){
int digit1 = (l1 != nullptr) ? l1->val : 0;
int digit2 = (l2 != nullptr) ? l2->val : 0;
sum = digit1 + digit2 + num;
if ( sum >= 10){
sum -= 10;
num = 1;
}
else{
num = 0;
}
ListNode* newNode = new ListNode(sum);
tail->next = newNode;
tail = tail->next;
l1 = (l1 != nullptr) ? l1->next : nullptr;
l2 = (l2 != nullptr) ? l2->next : nullptr;
}
return ret->next;
}
};
'Tech: Algorithm' 카테고리의 다른 글
[Leetcode] 6. Zigzag Conversion (0) | 2024.03.08 |
---|---|
[Leetcode] 5. Longest Palindromic Substring (0) | 2024.03.07 |
[Leetcode] 4. Median of Two Sorted Arrays (3) | 2024.03.06 |
[Leetcode] 3. Longest Substring Without Repeating Characters (2) | 2024.02.27 |
[Leetcode] 1. Two Sum (0) | 2024.02.26 |