728x90

Given an integer x, return true if x is palindrome integer.

An integer is a palindrome when it reads the same backward as forward.

  • For example, 121 is a palindrome while 123 is not.

 

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

 

Constraints:

  • -231 <= x <= 231 - 1

 

Follow up: Could you solve it without converting the integer to a string?

 

 

Solution

Golang 으로 숫자가 팰린드롬 인지를 확인하기 위해서 다음과 같이 구현 하였습니다.

 

func isPalindrome(x int) bool {
	sum := 0
	compare := x

	for x > 0 {
		r := x % 10
		sum = (sum * 10) + r
		x /= 10
	}
	return sum == compare
}

 

파라미터로 받아온 x 를 10 으로 나누고 나머지를 r 에 대입 합니다. r 은 x 의 1의 자리 숫자가 들어가게 됩니다.

sum 의 현재값에 10 을 곱하고 r 을 더하고 x 를 10 을 나누어 x 가 0 보다 작아 질때 까지 반복합니다.

 

이렇게 된 결과는 sum 은 x 의 값을 뒤집은 수가 됩니다.

728x90

'Algorithm > leetcode' 카테고리의 다른 글

Leetcode86. partition list (kotlin)  (0) 2023.04.22
Leetcode79. Word Search (w. kotlin)  (0) 2023.04.16