PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 3, 2022

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

 November 03, 2022     arrays, c#, lambda     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing