PowerShell Script to Reverse a Number with Output Example
$reversed = -join ($number.ToString().ToCharArray() | Reverse) to reverse a number in PowerShell by converting it to a string, reversing the characters, and joining them back.Examples
How to Think About It
Algorithm
Code
$number = 12345 $reversed = -join ($number.ToString().ToCharArray() | Reverse-Object) Write-Output $reversed
Dry Run
Let's trace reversing the number 12345 through the code
Convert number to string
12345 becomes '12345'
Split string into characters
'12345' becomes ['1','2','3','4','5']
Reverse characters and join
['1','2','3','4','5'] reversed is ['5','4','3','2','1'], joined to '54321'
| Step | Characters |
|---|---|
| Original | 1 2 3 4 5 |
| Reversed | 5 4 3 2 1 |
Why This Works
Step 1: Convert number to string
Using ToString() changes the number into text so we can handle each digit separately.
Step 2: Reverse characters
The Reverse-Object command flips the order of the characters in the array.
Step 3: Join reversed characters
Using -join combines the reversed characters back into a single string representing the reversed number.
Alternative Approaches
$number = 12345 $reversed = 0 while ($number -gt 0) { $digit = $number % 10 $reversed = $reversed * 10 + $digit $number = [math]::Floor($number / 10) } Write-Output $reversed
$number = 12345 $string = $number.ToString() $reversed = '' for ($i = $string.Length - 1; $i -ge 0; $i--) { $reversed += $string[$i] } Write-Output $reversed
Complexity: O(n) time, O(n) space
Time Complexity
Reversing the string requires visiting each digit once, so time grows linearly with the number of digits.
Space Complexity
Extra space is needed to hold the characters array and the reversed string, proportional to the number of digits.
Which Approach is Fastest?
The string reversal method is simple and fast for typical use, while arithmetic reversal avoids string overhead but is more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String reversal with Reverse | O(n) | O(n) | Simplicity and readability |
| Arithmetic reversal | O(n) | O(1) | Pure numeric operations without string conversion |
| Manual loop with indexing | O(n) | O(n) | Control over reversal process |