일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- EOI
- 선형대수
- 개발자
- omscs
- MATLAB
- C++
- zeros
- 프로그래머스
- 머신러닝
- 위니펙
- 컴퓨터과학과
- machine learning
- 조지아텍
- 주정부이민
- 방송통신대학교
- 방통대
- 온라인석사
- 알고리즘
- Deep learning
- cpp
- 캐나다 영주권
- 매트랩
- 기본
- 딥러닝
- LAA
- mpnp
- LV1
- leetcode
- Plotting
- 코딩테스트
Archives
- Today
- Total
Byte by Byte
2. Add Two Numbers.cpp 본문
🔑 링크드 리스트 개념 복습.
🔑 각 리스트의 수를 정수로 만든 후에 더하면 overflow. 따라서, 각 자리수마다 즉석해서 노드를 생성해야 한다.
/**
* 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) {}
* };
*/
// long long makenum (ListNode* x){
// long long res = 0;
// long long ten = 1;
// while(1){
// res+= ten*(x->val);
// if(x->next == nullptr) break;
// x= x->next;
// ten*=10;
// }
// cout << res << endl;
// return res;
// }
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
// long long output = makenum(l1) +makenum(l2);
// cout<< output;
ListNode*res = new ListNode(0);
ListNode*tmpres = res;
int num = 0;
while(1){
if(l1==nullptr && l2==nullptr) break;
int l1num =0;
if(l1!=nullptr){
l1num = l1->val;
l1 = l1->next;
}
int l2num =0;
if(l2!=nullptr){
l2num = l2->val;
l2 = l2->next;
}
int tmpnum = l1num+l2num + num;
// cout << tmpnum << " ";
if(tmpnum >=10){
num=1;
tmpnum-=10;
}
else num=0;
tmpres->next = new ListNode(tmpnum);
tmpres = tmpres->next;
if(l1==nullptr && l2==nullptr && num ==1){
tmpres->next = new ListNode(num);
}
}
return res->next;
}
};
'개발 로그 > 알고리즘' 카테고리의 다른 글
46. Permutations.cpp (0) | 2021.12.14 |
---|---|
118. Pascal's Triangle.cpp (0) | 2021.12.13 |
290. Word Pattern.cpp (0) | 2021.11.25 |
202. Happy Number.cpp (0) | 2021.11.24 |
766. Toeplitz Matrix.cpp (0) | 2021.11.22 |