Thursday, November 3, 2022

[FIXED] Why does this lambda function return the wrong answer

Issue

I'm trying to convert an int array in C# to a normal integer It works for most numbers but when i have the following code:

int[] digits = new int[] { 9,8,7,6,5,4,3,2,1,0 };
int bignumber = digits.Select((t, i) => t * Convert.ToInt32(Math.Pow(10, digits.Length - i - 1))).Sum();

it returns 1286608618 instead of 9876543210

I imagine it has something to do with the length of the array? But I don't understand how... If I remove the 0 on the end and make the array 9 numbers long it works fine. Stick any number in the 10th position and it breaks again.


Solution

Sum is going out of range of max Int32, which is 2147483647. Use Int64 (long) instead:

int[] digits = new int[] { 9,8,7,6,5,4,3,2,1,0 };
long bignumber = digits.Select((t, i) => t * Convert.ToInt64(Math.Pow(10, digits.Length - i - 1))).Sum();


Answered By - YK1
Answer Checked By - Terry (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.