Blowfelt82
asked on
Split a number into its composite digits and count.
I am looking for a way to count the digits that comprise a number - for example...
345 = 3 + 4 + 5 = 12
I have tried a few techniques to do this with Powershell, but all my solutions end up using the ASCII character code value of the digit rather than the actual number itself. I'm sure there must be a very easy way of achieving this?
345 = 3 + 4 + 5 = 12
I have tried a few techniques to do this with Powershell, but all my solutions end up using the ASCII character code value of the digit rather than the actual number itself. I'm sure there must be a very easy way of achieving this?
ASKER
Doesnt seem to work, I have the following...
for($i = 1; $i -lt 100; $i++) {
$current = "$i"
($current.Split("") | Measure-Object -Sum).Sum
}
But this isnt returning the results I would expect...
Note: I had to use $current.Split("") to make the code compile...
for($i = 1; $i -lt 100; $i++) {
$current = "$i"
($current.Split("") | Measure-Object -Sum).Sum
}
But this isnt returning the results I would expect...
Note: I had to use $current.Split("") to make the code compile...
Use the -split operator as Subsun posted, not the split method.
for($i = 1; $i -lt 100; $i++) {
$current = $i
($current -Split "" | Measure-Object -Sum).Sum
}
ASKER
Unfortunately when I try that command I get a 'You must provide a value expression on the right-hand side of the '-' operator.
Then you probably have a space after a hyphen somewhere. Select all the code above and paste and run.
ASKER
I think it must be something more sinister... I copied and pasted the following into a new window...
$num = "345"
($num -split "" | Measure -Sum).Sum
And am still getting the same issue?
EXCEPTION TYPE: System.Management.Automati on.ParseEx ception
MESSAGE: You must provide a value expression on the right-hand side of the '-' operator.
POSITION: At line:2 char:8 ($num -s <<<< plit "" | Measure -Sum).Sum
$num = "345"
($num -split "" | Measure -Sum).Sum
And am still getting the same issue?
EXCEPTION TYPE: System.Management.Automati
MESSAGE: You must provide a value expression on the right-hand side of the '-' operator.
POSITION: At line:2 char:8 ($num -s <<<< plit "" | Measure -Sum).Sum
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Good call, I am using powershell v1.0.0.0 - your final solution worked like a charm. Thanks for the help! Perhaps its time I move onto the latest version of powershell!
Open in new window