PS
Leetcode 2. Add Two Numbers
Bryan Lee
2022. 4. 30. 17:30
문제 이해
- 두 링크드 리스트의 덧셈을 구하라
해결 전략
- 두 개의 링크드 리스트를 각각 순회하면서,
값을 추출하고, 각각의 값을 더해줍니다.
구현
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode p, dummy = new ListNode(0);
p = dummy;
while(l1 != null || l2 != null || carry != 0){
if(l1 != null){
carry += l1.val;
l1 = l1.next;
}
if(l2 != null){
carry += l2.val;
l2 = l2.next;
}
ListNode tmp = new ListNode(carry%10);
p.next = tmp;
carry /= 10;
p = p.next;
}
return dummy.next;
}
}
피드백
- 효율적이고 깔끔한 코드를 짜는데 더 많은 관심을 가져야겠다.