본문 바로가기

코딩/leetcode

[leetcode]2번 두 수의 덧셈, 파이썬

문제

https://leetcode.com/problems/add-two-numbers/

 

Add Two Numbers - LeetCode

Can you solve this real interview question? Add Two Numbers - 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

leetcode.com

 

문제 : 두 수의 덧셈 : 역순으로 저장된 연결 리스트의 숫자를 더하여라

 

입력 :(2->4->3),+(5->6->4)

 

출력 : 7->0->8

 

1. 나의 풀이 방법

 

1. 역순으로 된 연결리스트를 원래대로 변환

2. 연결리스트를 리스트로 변환

3. 리스트를 문자로 바꾸고 이를 문자열로 바꾸어 하나의 숫자로 바꾸어준 다음에 합한 후 다시 문자열로 변환 후 연결리스트로 바꾸어준다.

 

class ListNode(object):
     def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution(object):
    def reverseList(self, head):
        node,prev = head,None
        while node:
            next,node.next = node.next,prev
            prev,node = node,next
        return prev
    
    #연결리스트 리스트로 전환        
    def toList(self,node): 
        List =[]
        if node :
            while node is not None:
                List.append(node.val)
                node= node.next
        return List
    
    #리스트 연결리스트로 전환
    def toLinked(self,List):
        if len(List)>0:
            head= ListNode(List[0])
            current = head
            head.next= current
            for i in range(1,len(List)):
                new = ListNode(List[i])
                current.next= new
                current = current.next
        
        return head
            
            
    def addTwoNumbers(self, l1, l2):
        a = self.toList(self.reverseList(l1))
        b = self.toList(self.reverseList(l2))
        
        #리스트를 문자열로 변환 -> 다시 정수로 변환하여 덧셈 과정 진행 이후 문자열로 변환해서 이를 연결리스트로 만들어준다. 
        resultStr = int (''.join(str(e) for e in a))+ \
                    int (''.join(str(e) for e in b))

        return self.reverseList(str(resultStr))