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
int start = curr;
while (start >= 10)
start /= 10;
This is more efficient than a ToString() approach which internally must implement a similar loop and has to construct (and parse) a string object on the way ...
variation on Anton's answer:
// cut down the number of divisions (assuming i is positive & 32 bits)
if (i >= 100000000) i /= 100000000;
if (i >= 10000) i /= 10000;
if (i >= 100) i /= 100;
if (i >= 10) i /= 10;
If you think Keltex's answer is ugly, try this one, it's REALLY ugly, and even faster. It does unrolled binary search to determine the length.
... leading code along the same lines
/* i<10000 */
if (i >= 100){
if (i >= 1000){
return i/1000;
}
else /* i<1000 */{
return i/100;
}
}
else /* i<100*/ {
if (i >= 10){
return i/10;
}
else /* i<10 */{
return i;
}
}
P.S. MartinStettner had the same idea.
Very easy method to get the Last digit:
int myInt = 1821;
int lastDigit = myInt - ((myInt/10)*10); // 1821 - 1820 = 1
int temp = i;
while (temp >= 10)
{
temp /= 10;
}
Result in temp
while (i > 10)
{
i = (Int32)Math.Floor((Decimal)i / 10);
}
// i is now the first int