본문 바로가기
Problem Solving/리트코드

[리트코드 leetcode] 2. Add Two Numbers

by ggyongi 2021. 4. 12.
반응형

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

 

# 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: ListNode, l2: ListNode) -> ListNode:
        
        l1_str :str = ''
        
        while l1:
            l1_str = str(l1.val)+l1_str
            l1 = l1.next
        
        l2_str :str = ''
        
        while l2:
            l2_str = str(l2.val)+l2_str
            l2 = l2.next
            
        sum=0
        sum = int(l1_str) + int(l2_str)
        
        list=[]
        for i in str(sum):
            list.append(i)
        
        answer = None
        
        while list:
            answer = ListNode(list.pop(0),answer)
        return answer
        

 

# 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: ListNode, l2: ListNode) -> ListNode:
        
        l1_num, l2_num = 0, 0
        i,j = 0,0
        
       
        while l1:
            l1_num += (l1.val*(10**i))
            l1 = l1.next
            i +=1
        
        while l2:
            l2_num += (l2.val*(10**j))
            l2 = l2.next
            j +=1
            
        sum=0
        sum = l1_num + l2_num
        
        list=[]
        for i in str(sum):
            list.append(i)
        
        answer = None
        
        while list:
            answer = ListNode(list.pop(0),answer)
        return answer
        
 

비전공자 네카라 신입 취업 노하우

시행착오 끝에 얻어낸 취업 노하우가 모두 담긴 전자책!

kmong.com

댓글