0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Find Sum of Digits

Use $sum = ($number.ToString().ToCharArray() | ForEach-Object { [int]$_ }) | Measure-Object -Sum | Select-Object -ExpandProperty Sum to find the sum of digits of a number in PowerShell.
📋

Examples

Input123
Output6
Input405
Output9
Input0
Output0
🧠

How to Think About It

To find the sum of digits, convert the number to a string so you can look at each digit separately. Then, change each character back to a number and add them all together.
📐

Algorithm

1
Get the input number.
2
Convert the number to a string.
3
Split the string into individual characters.
4
Convert each character back to an integer.
5
Add all the integers together.
6
Return the sum.
💻

Code

powershell
$number = Read-Host 'Enter a number'
$digits = $number.ToString().ToCharArray()
$sum = 0
foreach ($digit in $digits) {
    $sum += [int]$digit
}
Write-Output "Sum of digits: $sum"
Output
Enter a number: 123 Sum of digits: 6
🔍

Dry Run

Let's trace the input 123 through the code

1

Convert number to string and split

Input: 123 -> '123' -> ['1', '2', '3']

2

Convert each character to integer and sum

1 + 2 + 3 = 6

DigitInteger ValueRunning Sum
111
223
336
💡

Why This Works

Step 1: Convert number to string

Using ToString() lets us treat the number as text to access each digit.

Step 2: Split into characters

Splitting into characters lets us handle each digit separately.

Step 3: Convert characters to integers and sum

Casting each character to [int] converts it back to a number so we can add them.

🔄

Alternative Approaches

Using Measure-Object
powershell
$number = Read-Host 'Enter a number'
$sum = ($number.ToString().ToCharArray() | ForEach-Object { [int]$_ }) | Measure-Object -Sum | Select-Object -ExpandProperty Sum
Write-Output "Sum of digits: $sum"
This method uses PowerShell's built-in Measure-Object to sum digits, making the code shorter and more readable.
Using array sum with pipeline
powershell
$number = Read-Host 'Enter a number'
$sum = 0
$number.ToString().ToCharArray() | ForEach-Object { $sum += [int]$_ }
Write-Output "Sum of digits: $sum"
This approach uses a pipeline with ForEach-Object to accumulate the sum, which is simple and clear.

Complexity: O(n) time, O(n) space

Time Complexity

The script processes each digit once, so time grows linearly with the number of digits.

Space Complexity

Converting the number to a character array uses extra space proportional to the number of digits.

Which Approach is Fastest?

Using Measure-Object is concise and efficient, but all methods have similar linear time complexity.

ApproachTimeSpaceBest For
Loop with foreachO(n)O(n)Clear step-by-step logic
Measure-ObjectO(n)O(n)Concise and readable code
Pipeline with ForEach-ObjectO(n)O(n)Simple and idiomatic PowerShell
💡
Always convert the number to a string first to easily access each digit.
⚠️
Trying to add digits directly without converting them to integers causes errors or wrong results.