Reputation: 25
public static int SumDigits(int number)
{
return (int)number.ToString().Sum(x => char.IsNumber(x) ? char.GetNumericValue(x) : 0);
}
What is the (int)
after return
means.
Its perfectly running, just need to understand it, thanks.
Upvotes: 0
Views: 48
Reputation: 8503
The GetNumericValue
method returns a double
. The (int)
is a cast that converts the returned double
to int
.
Keep in mind that it truncates the decimal part which should be okay for numeric char values. There are methods like Convert.ToInt32(doubleValue)
or (int) Math.Round(doubleValue)
that round the result instead of truncating it.
Upvotes: 3