본문 바로가기
코딩테스트/LeetCode 문제

LeetCode [알고리즘] Palindrome Number

by junjunjun 2021. 12. 22.
반응형

문제 

입력된 숫자가 회문 숫자인지 확인하시오

(회문 ex) (o) -> 010, 123321,  (x) ->123 , 1100

 

나의 풀이

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x <0: return False
        a = str(x)
        a2 = a[::-1]
        if a[0:len(a)//2] == a2[0:len(a)//2]:
            return True 
        else:
            return False

파이썬은 문자열을 다루기 쉽기에 문자열을 뒤집어서 비교해 주었다.

 

Follow up : 문자열 변환 없이 풀어라.

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x <0: return False
        n= []
        while x != 0:
            n.append(x%10)
            x = x//10
        print(n)
        i = 0
        j = len(n)
        while i <j:
            if n[i] != n[j-1]:
                return False
            i+=1;
            j-=1;
        return True

10으로 나눠주어 각각의 자릿수를 구하여 리스트에 넣어준 뒤

비교하였다.

 

다른 사람 풀이

def isPalindrome(self, x: int) -> bool:
	if x < 0:
		return False
	
	return str(x) == str(x)[::-1]

그냥 순서를 거꾸로 해서 비교해주면 되는데

나는 왜 절반을 나누었을까..

 

Follow up : 문자열 변환 없이 풀어라.

def isPalindrome(self, x: int) -> bool:
	if x<0:
		return False

	inputNum = x
	newNum = 0
	while x>0:
		newNum = newNum * 10 + x%10
		x = x//10
	return newNum == inputNum

x를 10으로 나누어 주어 1의 자릿수 부터 거꾸로 새로운 변수를 생성해 준다.

해당 변수와 x를 비교하여 결과 값을 리턴해 준다.

 

접근 방식은 비슷한데 나는 왜이리 복잡하게 풀었을까.

반응형

'코딩테스트 > LeetCode 문제' 카테고리의 다른 글

LeetCode [알고리즘] Roman to Integer  (0) 2021.12.22
LeetCode [알고리즘] Two Sum  (0) 2021.12.21

댓글