In C#, what's the best way to get the 1st digit in an int? The method I came up with is to turn the int into a string, find the 1st char of the string, then turn it back to an int.
int start = Convert.ToInt32(curr.ToString().Substring(0, 1));
While this does the job, it feels like there is probably a good, simple, math-based solution to such a problem. String manipulation feels clunky.
Edit: irrespective of speed differences, mystring[0] instead of Substring() is still just string manipulation
To finding first digit of a number is little expensive than last digit. To find first digit of a number we divide the given number by 10 until number is greater than 10. At the end we are left with the first digit.
printf("First digit of the entered number is: %d \n", firstDigit); printf("Last digit of the entered number is: %d", lastDigit); // Displaying output printf("First digit of the entered number is: %d \n", firstDigit); printf("Last digit of the entered number is: %d", lastDigit);
The first digit 1 is in the Hundreds place and has a value of One hundred. The second digit 1 is in the Tens place and has a value of Ten. The digit 2 is in the Ones place and has a value of Two.
Firstly, you must decide on what you mean by "best" solution, of course that takes into account the efficiency of the algorithm, its readability/maintainability, and the likelihood of bugs creeping up in the future. Careful unit tests can generally avoid those problems, however.
I ran each of these examples 10 million times, and the results value is the number of ElapsedTicks
that have passed.
Without further ado, from slowest to quickest, the algorithms are:
int firstDigit = (int)(Value.ToString()[0]) - 48;
Results:
12,552,893 ticks
int firstDigit = (int)(Value / Math.Pow(10, (int)Math.Floor(Math.Log10(Value))));
Results:
9,165,089 ticks
while (number >= 10) number /= 10;
Results:
6,001,570 ticks
int firstdigit; if (Value < 10) firstdigit = Value; else if (Value < 100) firstdigit = Value / 10; else if (Value < 1000) firstdigit = Value / 100; else if (Value < 10000) firstdigit = Value / 1000; else if (Value < 100000) firstdigit = Value / 10000; else if (Value < 1000000) firstdigit = Value / 100000; else if (Value < 10000000) firstdigit = Value / 1000000; else if (Value < 100000000) firstdigit = Value / 10000000; else if (Value < 1000000000) firstdigit = Value / 100000000; else firstdigit = Value / 1000000000;
Results:
1,421,659 ticks
if (i >= 100000000) i /= 100000000; if (i >= 10000) i /= 10000; if (i >= 100) i /= 100; if (i >= 10) i /= 10;
Results:
1,399,788 ticks
Note:
each test calls Random.Next()
to get the next int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With