PowerShell Script to Check Palindrome Number
-join and Reverse, then compares it to the original string to check if it's a palindrome.Examples
How to Think About It
Algorithm
Code
function Test-PalindromeNumber { param([int]$number) $str = $number.ToString() $rev = -join ($str.ToCharArray() | Reverse) if ($str -eq $rev) { Write-Output "$number is a palindrome number." } else { Write-Output "$number is not a palindrome number." } } Test-PalindromeNumber -number 121 Test-PalindromeNumber -number 123
Dry Run
Let's trace the number 121 through the code
Convert number to string
Input: 121 -> String: '121'
Reverse string characters
'121' reversed -> '121'
Compare original and reversed
'121' equals '121' -> True, so palindrome
| Original String | Reversed String | Palindrome? |
|---|---|---|
| 121 | 121 | Yes |
Why This Works
Step 1: Convert number to string
Using ToString() changes the number into text so we can check each character.
Step 2: Reverse the string
We split the string into characters, reverse their order with Reverse, then join them back with -join.
Step 3: Compare original and reversed
If the reversed string matches the original, the number reads the same forwards and backwards, so it is a palindrome.
Alternative Approaches
function Test-PalindromeNumberArithmetic { param([int]$number) $original = $number $reverse = 0 while ($number -gt 0) { $digit = $number % 10 $reverse = $reverse * 10 + $digit $number = [math]::Floor($number / 10) } if ($original -eq $reverse) { Write-Output "$original is a palindrome number." } else { Write-Output "$original is not a palindrome number." } } Test-PalindromeNumberArithmetic -number 121 Test-PalindromeNumberArithmetic -number 123
function Test-PalindromeNumberSimple { param([int]$number) $str = $number.ToString() if ($str -eq (-join ($str.ToCharArray() | Reverse))) { Write-Output "$number is a palindrome number." } else { Write-Output "$number is not a palindrome number." } } Test-PalindromeNumberSimple -number 121 Test-PalindromeNumberSimple -number 123
Complexity: O(n) time, O(n) space
Time Complexity
The script processes each digit once to reverse the string, so time grows linearly with the number of digits.
Space Complexity
Extra space is used to store the reversed string, proportional to the number of digits.
Which Approach is Fastest?
The arithmetic method avoids string operations and can be faster for very large numbers, but the string method is simpler and clearer for most cases.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String reversal | O(n) | O(n) | Simplicity and readability |
| Arithmetic reversal | O(n) | O(1) | Performance with large numbers |