0009. Palindrome Number

9. Palindrome Number #

Problem #

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

Example 1:

Input: 121
Output: true

Example 2:

Input: -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: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

Problem Summary #

Determine whether an integer is a palindrome. A palindrome number refers to an integer that reads the same in forward order (from left to right) and reverse order (from right to left).

Solution Approach #

  • Determine whether an integer is a palindrome.
  • Easy problem. Note that there may be negative numbers; negative numbers, single-digit numbers, and 10 are not palindromes. Other integers are then checked according to the palindrome rules.

Code #


package leetcode

import "strconv"

// Solution one
func isPalindrome(x int) bool {
	if x < 0 {
		return false
	}
	if x == 0 {
		return true
	}
	if x%10 == 0 {
		return false
	}
	arr := make([]int, 0, 32)
	for x > 0 {
		arr = append(arr, x%10)
		x = x / 10
	}
	sz := len(arr)
	for i, j := 0, sz-1; i <= j; i, j = i+1, j-1 {
		if arr[i] != arr[j] {
			return false
		}
	}
	return true
}

// Solution two: convert number to string
func isPalindrome1(x int) bool {
	if x < 0 {
		return false
	}
	if x < 10 {
		return true
	}
	s := strconv.Itoa(x)
	length := len(s)
	for i := 0; i <= length/2; i++ {
		if s[i] != s[length-1-i] {
			return false
		}
	}
	return true
}



Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文