Palindrome Number

easy · math

Palindrome Number

Given an integer, return true if it is a palindrome (reads the same forward and backward). Converting to string is easy but not required; the numeric approach avoids extra space.

Function signature

func IsPalindrome(x int) bool

Inputs / outputs

  • x: integer.
  • Return: true if palindrome, else false.

Example

121 -> true
-121 -> false (negative sign)
10 -> false (leading zero would be needed)

Constraints

  • Fits in 32-bit signed integer.

Core idea (near-solution)

Reverse only half the number and compare. This avoids overflow and extra work.

Invariant: after each step, rev is the reverse of the processed suffix of x.

Algorithm (step-by-step)

  1. If x < 0, return false. If x % 10 == 0 and x != 0, return false.
  2. Build rev by extracting digits until rev >= x.
  3. The number is a palindrome if x == rev (even length) or x == rev/10 (odd length).

Correctness sketch

  • Invariant: after each step, rev is the reverse of the processed suffix of x.
  • The formula/transform follows from number properties or monotonicity.
  • Each iteration preserves the mathematical invariant.
  • Thus the computed value matches the definition of the problem.

Trace (hand walkthrough)

Trace Walkthrough
Example input:
121 -> true
-121 -> false (negative sign)
10 -> false (leading zero would be needed)

Walk:
- x=121: rev=1, x=12; rev=12, x=1 -> x==rev/10 -> true
- x=-121 -> negative -> false; x=10 ends with 0 -> false

Pitfalls to avoid

  • Reversing the full number (can overflow).
  • Treating negative numbers as palindromes.
  • Forgetting the trailing zero rule.

Complexity

  • Time: O(log10 x).
  • Extra space: O(1).

Implementation notes (Go)

  • Integer division and modulo are safe for non-negative numbers.
Run tests to see results
No issues detected