简体   繁体   中英

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM