Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this lambda function return the wrong answer

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading