문제
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 contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
풀이
list를 순회하면서 실제 덧셈을 하는 것 같이 계산을 해준다.
받아올림할 변수인 carry를 잘 관리하는 것이 핵심.
Time Complexity : $O(n)$
코드
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry=0;
ListNode *ans=new ListNode(0);
ListNode *p=l1;
ListNode *q=l2;
ListNode *now=ans;
while(p!=NULL || q!=NULL)
{
int s =(p?p->val:0)+(q?q->val:0)+carry;
carry = s/10;
now->next = new ListNode(s%10);
now = now->next;
if(p) p=p->next;
if(q) q=q->next;
}
if(carry) now->next = new ListNode(carry);
return ans->next;
}
};
'PS > leetcode' 카테고리의 다른 글
[leetcode] 6. ZigZag Conversion (0) | 2019.04.28 |
---|---|
[leetcode] 5. Longest Palindromic Substring (0) | 2019.04.28 |
[leetcode] 4. Median of Two Sorted Arrays (0) | 2019.04.28 |
[leetcode] 3. Longest Substring Without Repeating Characters (0) | 2019.04.28 |
[leetcode] 1. Two Sum (0) | 2019.04.28 |