89

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,
  • get the 1st char of the string, and
  • turn the char into an int.

Like:

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

4
  • That's is even slower than the recursive method. =)
    – J. Steen
    Mar 31, 2009 at 15:20
  • my bad, i forgot to reset the stopwatch =), it's really slower than others
    – Deltax76
    Mar 31, 2009 at 15:24
  • 2
    This will fail on negative numbers.
    – plinth
    Apr 14, 2010 at 13:54
  • 2
    the first digit of an int is always 1 with zero suppression (01010101010100101011011011100101) LOL Nov 4, 2010 at 1:12

26 Answers 26

232

Benchmarks

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:

Converting to a string, take first character

int firstDigit = (int)(Value.ToString()[0]) - 48;

Results:

12,552,893 ticks

Using a logarithm

int firstDigit = (int)(Value / Math.Pow(10, (int)Math.Floor(Math.Log10(Value))));

Results:

9,165,089 ticks

Looping

while (number >= 10)
    number /= 10;

Results:

6,001,570 ticks

Conditionals

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

Unrolled & optimized loop

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

18
  • Ran them on what set of integers?
    – mqp
    Mar 31, 2009 at 15:43
  • 22
    This is soooooo trivial. I appreciate what you've done and it's quite informative, but it's so overkill for 99% of applications. I'm afraid some novice programmers might get a bad impression. (hard-core, premature optimizations over readability) It's still fun, though. :) Mar 31, 2009 at 17:46
  • 3
    +1 for benchmarks, but I agree this is total overkill. If you are THAT worried about performance then you probably shouldn't be using C# in the first place :)
    – GrahamS
    Apr 15, 2009 at 17:14
  • 17
    +1 - Great stuff. This is the kind of gold-plated, deluxe-model overkill that just makes it obvious that you love coding. Many kudos to you. And no, Stuart, I don't think this will pollute the minds of unsuspecting newbies. Hopefully, it will teach them to develop a love of software. Apr 22, 2009 at 13:25
  • 2
    @Vikash - casting a char to an int evaluates to the code point of the character, so casting the character 0 evaluates to 48. Subtracting 48 effectively does a conversion to an integer. As another example, casting the character 5 to an int evaluates to 53, and subtracting 48 from that results in 5.
    – John Rasch
    Feb 13, 2017 at 15:49
131

Here's how

int i = Math.Abs(386792);
while(i >= 10)
    i /= 10;

and i will contain what you need

0
31

Try this

public int GetFirstDigit(int number) {
  if ( number < 10 ) {
    return number;
  }
  return GetFirstDigit ( (number - (number % 10)) / 10);
}

EDIT

Several people have requested the loop version

public static int GetFirstDigitLoop(int number)
{
    while (number >= 10)
    {
        number = (number - (number % 10)) / 10;
    }
    return number;
}
10
  • 1
    Recursion for something like this... Shame on you. Put a loop in there.
    – Welbog
    Mar 31, 2009 at 14:51
  • @Welbog :), Normally I would. But I have a lot of nostalgia around this particular question. It almost exactly the first questions I was ever asked for a CS assignment. At the time I wrote essentially this solution.
    – JaredPar
    Mar 31, 2009 at 14:52
  • This is the case where "nice" = slow
    – Keltex
    Mar 31, 2009 at 14:53
  • 1
    I'd hope the optimizer would see the first version as something that can be tail-call optimized, in which case it wouldn't be any slower.
    – rmeador
    Mar 31, 2009 at 14:57
  • 1
    But, @Jared, the subtraction of the last digit is completely unnecessary here. Just divide by 10. Mar 31, 2009 at 15:01
27

The best I can come up with is:

int numberOfDigits = Convert.ToInt32(Math.Floor( Math.Log10( value ) ) );

int firstDigit = value / Math.Pow( 10, numberOfDigits );
2
  • You can avoid unneccesary conversions between integers and doubles by using divisor=Convert.ToInt32(Math.Pow(10, Math.Floor(Math.Log10(value)))); firstDigit = value/divisor; Mar 31, 2009 at 15:10
  • Unfortunately this does not work when value is 1 (returns 0) or if value is negative. The fix is int numberOfDigits = 1 + Convert.ToInt32(Math.Floor(Math.Log10(Math.Abs(value))));
    – DanDan
    Jul 31, 2011 at 21:14
18

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;
6
  • I think I would just leave it at /10 and /1000. You still get the advantage of dividing more aggressively, but with slightly less mess. +1 for creativity :) Mar 31, 2009 at 15:29
  • Reminds me of a function in bcl someone discovered, the method was pretty ugly to read, but it was basically doing looping compares, and was ganging compares into groups of ten or so, knowing that modern cpus would be able to better handle a group of compares at a time. Mar 31, 2009 at 15:38
  • It's only fantastically ugly because C# doesn't have a way to generate those consts at compile-time (and doing it at runtime would be more expensive than what you're trying to prevent). In a language like Lisp where you control eval time, the fast way and the elegant way are the same. :-)
    – Ken
    Mar 31, 2009 at 15:41
  • Unrolling a loop is certainly better than a crap-ton of if/else statements. It's both elegant and performant.
    – Randolpho
    Mar 31, 2009 at 15:45
  • 3
    if you make the first "if" a "while", it also works with 64-bit (but is even "uglier"). +1 Mar 31, 2009 at 15:49
5
int myNumber = 8383;
char firstDigit = myNumber.ToString()[0];
// char = '8'
5
  • Isn't this identical to what I posted? It just uses [] instead of Substring
    – Dinah
    Mar 31, 2009 at 14:50
  • No: it returns a character rather than a string and the [] lookup should be faster Mar 31, 2009 at 14:51
  • That's true, but it's still the same basic method -- parse the string representation. I think @Dinah is looking for something... you know.... different.
    – Randolpho
    Mar 31, 2009 at 14:52
  • @Randolpho: exactly. Sorry if I was unclear about that. I updated the question to clarify.
    – Dinah
    Mar 31, 2009 at 14:57
  • I also would return firstDigit-'0' to get the int. (it works in c ... i guess it does in c#) Mar 31, 2009 at 15:09
5

Had the same idea as Lennaert

int start = number == 0 ? 0 : number / (int) Math.Pow(10,Math.Floor(Math.Log10(Math.Abs(number))));

This also works with negative numbers.

4

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.

2
  • @Rasch: Ah, the rapture! It should be hidden, brought out for special occasions only, and read in hushed tones... Who says programming has no soul? Mar 31, 2009 at 18:05
  • how about i=(...moreugly...)i>=100?i>=1000?i/1000:i/100:i>=10?i/10:i; Apr 14, 2010 at 14:10
3

Very simple (and probably quite fast because it only involves comparisons and one division):

if(i<10)
   firstdigit = i;
else if (i<100)
   firstdigit = i/10;
else if (i<1000)
   firstdigit = i/100;
else if (i<10000)
   firstdigit = i/1000;
else if (i<100000)
   firstdigit = i/10000;
else (etc... all the way up to 1000000000)
24
  • 1
    And then there's 10k, 100k, 1mil, 10mil, 100mil and so on? Mar 31, 2009 at 14:50
  • I would do it this way. A lot more efficient than that recursive function.
    – Keltex
    Mar 31, 2009 at 14:51
  • This answer is the best of the bunch.
    – Brian
    Mar 31, 2009 at 14:54
  • Efficiency bought at the expense of really really really ugly, repetitive, unmaintainable code. What if you had skipped a rank accidentally? Whoops.
    – Randolpho
    Mar 31, 2009 at 14:54
  • You really should reorder those conditions so that the most likely are at the top... Mar 31, 2009 at 14:56
3

An obvious, but slow, mathematical approach is:

int firstDigit = (int)(i / Math.Pow(10, (int)Math.Log10(i))));
6
  • Time it, it shouldn't be slow at all. This was going to be my suggestion, and given that it's a purely mathematical solution with no looping, it's possibly faster than many solutions here. Keep in mind that every x86 processor sold today has a very, very fast and capable floating point processor.
    – Adam Davis
    Mar 31, 2009 at 15:10
  • I think you really should use Math.Log10 here Mar 31, 2009 at 15:17
  • Thanks, Martin - I don't use .NET math libraries much and forgot it was Log and Log10 instead of Log and Ln.
    – mqp
    Mar 31, 2009 at 15:20
  • Well, Adam, at the very least it needs to take 10^(N-1) (n being number of digits) plus it needs to take a logarithm. Compared to a looping answer (where you're dividing N - 1 times) it seems to me that it must be at least a little slower. But I am regularly surprised by benchmarks, so who knows.
    – mqp
    Mar 31, 2009 at 15:23
  • 1
    Besides, the OP asked for a more meaningful expression, without regard to performance, and this is the most direct (mathematical) way to express what is being sought.
    – harpo
    Mar 31, 2009 at 16:29
3
int temp = i;
while (temp >= 10)
{
    temp /= 10;
}

Result in temp

1
  • @ck: What rounding issued? Division is integer-division in this case, each division exactly cuts off the last digit ... Mar 31, 2009 at 14:58
3

I know it's not C#, but it's surprising curious that in python the "get the first char of the string representation of the number" is the faster!

EDIT: no, I made a mistake, I forgot to construct again the int, sorry. The unrolled version it's the fastest.

$ cat first_digit.py
def loop(n):
    while n >= 10:
        n /= 10
    return n

def unrolled(n):
    while n >= 100000000: # yea... unlimited size int supported :)
        n /= 100000000
    if n >= 10000:
        n /= 10000
    if n >= 100:
        n /= 100
    if n >= 10:
        n /= 10
    return n

def string(n):
    return int(str(n)[0])
$ python -mtimeit -s 'from first_digit import loop as test' \
    'for n in xrange(0, 100000000, 1000): test(n)'
10 loops, best of 3: 275 msec per loop
$ python -mtimeit -s 'from first_digit import unrolled as test' \
    'for n in xrange(0, 100000000, 1000): test(n)'
10 loops, best of 3: 149 msec per loop
$ python -mtimeit -s 'from first_digit import string as test' \
    'for n in xrange(0, 100000000, 1000): test(n)'
10 loops, best of 3: 284 msec per loop
$
3
  • But does it convert it back to an integer?
    – Samuel
    Mar 31, 2009 at 19:23
  • woops, now it makes a sense -.-
    – ZeD
    Mar 31, 2009 at 19:27
  • well he could say it was IronPython to make this slightly less off-topic
    – Ravi
    Oct 7, 2009 at 21:55
3

I just stumbled upon this old question and felt inclined to propose another suggestion since none of the other answers so far returns the correct result for all possible input values and it can still be made faster:

public static int GetFirstDigit( int i )
{
    if( i < 0 && ( i = -i ) < 0 ) return 2;
    return ( i < 100 ) ? ( i < 1 ) ? 0 : ( i < 10 )
            ? i : i / 10 : ( i < 1000000 ) ? ( i < 10000 )
            ? ( i < 1000 ) ? i / 100 : i / 1000 : ( i < 100000 )
            ? i / 10000 : i / 100000 : ( i < 100000000 )
            ? ( i < 10000000 ) ? i / 1000000 : i / 10000000
            : ( i < 1000000000 ) ? i / 100000000 : i / 1000000000;
}

This works for all signed integer values inclusive -2147483648 which is the smallest signed integer and doesn't have a positive counterpart. Math.Abs( -2147483648 ) triggers a System.OverflowException and - -2147483648 computes to -2147483648.

The implementation can be seen as a combination of the advantages of the two fastest implementations so far. It uses a binary search and avoids superfluous divisions. A quick benchmark with the index of a loop with 100,000,000 iterations shows that it is twice as fast as the currently fastest implementation.

It finishes after 2,829,581 ticks.

For comparison I also measured a corrected variant of the currently fastest implementation which took 5,664,627 ticks.

public static int GetFirstDigitX( int i )
{
    if( i < 0 && ( i = -i ) < 0 ) return 2;
    if( i >= 100000000 ) i /= 100000000;
    if( i >= 10000 ) i /= 10000;
    if( i >= 100 ) i /= 100;
    if( i >= 10 ) i /= 10;
    return i;
}

The accepted answer with the same correction needed 16,561,929 ticks for this test on my computer.

public static int GetFirstDigitY( int i )
{
    if( i < 0 && ( i = -i ) < 0 ) return 2;
    while( i >= 10 )
        i /= 10;
    return i;
}

Simple functions like these can easily be proven for correctness since iterating all possible integer values takes not much more than a few seconds on current hardware. This means that it is less important to implement them in a exceptionally readable fashion as there simply won't ever be the need to fix a bug inside them later on.

1

Did some tests with one of my co-workers here, and found out most of the solutions don't work for numbers under 0.

  public int GetFirstDigit(int number)
    {
        number = Math.Abs(number); <- makes sure you really get the digit!

        if (number < 10)
        {
            return number;
        }
        return GetFirstDigit((number - (number % 10)) / 10);
    }
1

Using all the examples below to get this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Benfords
{
    class Program
    {
        static int FirstDigit1(int value)
        {
            return Convert.ToInt32(value.ToString().Substring(0, 1));
        }

        static int FirstDigit2(int value)
        {
            while (value >= 10) value /= 10;
            return value;
        }


        static int FirstDigit3(int value)
        {
            return (int)(value.ToString()[0]) - 48;
        }

        static int FirstDigit4(int value)
        {
            return (int)(value / Math.Pow(10, (int)Math.Floor(Math.Log10(value))));
        }

        static int FirstDigit5(int value)
        {
            if (value < 10) return value;
            if (value < 100) return value / 10;
            if (value < 1000) return value / 100;
            if (value < 10000) return value / 1000;
            if (value < 100000) return value / 10000;
            if (value < 1000000) return value / 100000;
            if (value < 10000000) return value / 1000000;
            if (value < 100000000) return value / 10000000;
            if (value < 1000000000) return value / 100000000;
            return value / 1000000000;
        }

        static int FirstDigit6(int value)
        {
            if (value >= 100000000) value /= 100000000;
            if (value >= 10000) value /= 10000;
            if (value >= 100) value /= 100;
            if (value >= 10) value /= 10;
            return value;
        }

        const int mcTests = 1000000;

        static void Main(string[] args)
        {
            Stopwatch lswWatch = new Stopwatch();
            Random lrRandom = new Random();

            int liCounter;

            lswWatch.Start();
            for (liCounter = 0; liCounter < mcTests; liCounter++)
                FirstDigit1(lrRandom.Next());
            lswWatch.Stop();
            Console.WriteLine("Test {0} = {1} ticks", 1, lswWatch.ElapsedTicks);

            lswWatch.Reset();
            lswWatch.Start();
            for (liCounter = 0; liCounter < mcTests; liCounter++)
                FirstDigit2(lrRandom.Next());
            lswWatch.Stop();
            Console.WriteLine("Test {0} = {1} ticks", 2, lswWatch.ElapsedTicks);

            lswWatch.Reset();
            lswWatch.Start();
            for (liCounter = 0; liCounter < mcTests; liCounter++)
                FirstDigit3(lrRandom.Next());
            lswWatch.Stop();
            Console.WriteLine("Test {0} = {1} ticks", 3, lswWatch.ElapsedTicks);

            lswWatch.Reset();
            lswWatch.Start();
            for (liCounter = 0; liCounter < mcTests; liCounter++)
                FirstDigit4(lrRandom.Next());
            lswWatch.Stop();
            Console.WriteLine("Test {0} = {1} ticks", 4, lswWatch.ElapsedTicks);

            lswWatch.Reset();
            lswWatch.Start();
            for (liCounter = 0; liCounter < mcTests; liCounter++)
                FirstDigit5(lrRandom.Next());
            lswWatch.Stop();
            Console.WriteLine("Test {0} = {1} ticks", 5, lswWatch.ElapsedTicks);

            lswWatch.Reset();
            lswWatch.Start();
            for (liCounter = 0; liCounter < mcTests; liCounter++)
                FirstDigit6(lrRandom.Next());
            lswWatch.Stop();
            Console.WriteLine("Test {0} = {1} ticks", 6, lswWatch.ElapsedTicks);

            Console.ReadLine();
        }
    }
}

I get these results on an AMD Ahtlon 64 X2 Dual Core 4200+ (2.2 GHz):

Test 1 = 2352048 ticks
Test 2 = 614550 ticks
Test 3 = 1354784 ticks
Test 4 = 844519 ticks
Test 5 = 150021 ticks
Test 6 = 192303 ticks

But get these on a AMD FX 8350 Eight Core (4.00 GHz)

Test 1 = 3917354 ticks
Test 2 = 811727 ticks
Test 3 = 2187388 ticks
Test 4 = 1790292 ticks
Test 5 = 241150 ticks
Test 6 = 227738 ticks

So whether or not method 5 or 6 is faster depends on the CPU, I can only surmise this is because the branch prediction in the command processor of the CPU is smarter on the new processor, but I'm not really sure.

I dont have any Intel CPUs, maybe someone could test it for us?

1

Check this one too:

int get1digit(Int64 myVal)
{
    string q12 = myVal.ToString()[0].ToString();
    int i = int.Parse(q12);
    return i;
}

Also good if you want multiple numbers:

int get3digit(Int64 myVal) //Int64 or whatever numerical data you have
{
    char mg1 = myVal.ToString()[0];
    char mg2 = myVal.ToString()[1];
    char mg3 = myVal.ToString()[2];
    char[] chars = { mg1, mg2, mg3 };
    string q12= new string(chars);
    int i = int.Parse(q12);
    return i;
}
5
  • Could your add some explanation to your answer? This question already has 24 other answers - it'd be good to know why we should use yours rather than the others.
    – Wai Ha Lee
    Apr 17, 2019 at 20:06
  • With the original solution, i got some bugs using large numbers. My solution is cleaner. You're welcome. Apr 17, 2019 at 20:42
  • Your solution fails for -1.
    – Wai Ha Lee
    Apr 17, 2019 at 20:44
  • :) use this then : if (myVal.ToString()[0]!='-') {....} and - sign is not a number ! Apr 17, 2019 at 20:51
  • Why not check the number is not negative instead of checking the string?
    – Wai Ha Lee
    Apr 17, 2019 at 20:52
0
while (i > 10)
{
   i = (Int32)Math.Floor((Decimal)i / 10);
}
// i is now the first int
3
  • Why are you converting to Decimal? Also Floor is not needed. Mar 31, 2009 at 14:57
  • It was there for potential rounding issues, which isn't actually needed.
    – cjk
    Mar 31, 2009 at 15:02
  • Should be while(i >= 10) or this will fail for multiples of 10. Mar 31, 2009 at 19:26
0

Non iterative formula:

public static int GetHighestDigit(int num)
{
    if (num <= 0)
       return 0; 

    return (int)((double)num / Math.Pow(10f, Math.Floor(Math.Log10(num))));
}
1
  • Implementation of Log is iterative as it requires a root-finding algorithm Mar 31, 2009 at 16:16
0

Just to give you an alternative, you could repeatedly divide the integer by 10, and then rollback one value once you reach zero. Since string operations are generally slow, this may be faster than string manipulation, but is by no means elegant.

Something like this:

while(curr>=10)
     curr /= 10;
2
  • Make the while-condition (curr > 10) and you do not need prevValue Mar 31, 2009 at 14:57
  • >= is needed. The first digit of 10 should be 1, not 10
    – Dinah
    Mar 31, 2009 at 15:27
0
start = getFirstDigit(start);   
public int getFirstDigit(final int start){
    int number = Math.abs(start);
    while(number > 10){
        number /= 10;
    }
    return number;
}

or

public int getFirstDigit(final int start){
  return getFirstDigit(Math.abs(start), true);
}
private int getFirstDigit(final int start, final boolean recurse){
  if(start < 10){
    return start;
  }
  return getFirstDigit(start / 10, recurse);
}
1
  • Should work now. Also added recursive function with trap for abs.
    – sdellysse
    May 1, 2009 at 1:51
0
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 ...

0

Very easy method to get the Last digit:

int myInt = 1821;

int lastDigit = myInt - ((myInt/10)*10); // 1821 - 1820 = 1
2
  • 3
    That's nice, but the question is to get the First digit, not the Last.
    – Dinah
    Apr 24, 2010 at 18:01
  • @Daniel Because int lastDigigt = myInt % 10; is just too obvious?
    – mortb
    Sep 9, 2021 at 14:03
0
int i = 4567789;
int digit1 = int.Parse(i.ToString()[0].ToString());
0
0

This is what I usually do ,please refer my function below :

This function can extract first number occurance from any string you can modify and use this function according to your usage

   public static int GetFirstNumber(this string strInsput)
    {
        int number = 0;
        string strNumber = "";
        bool bIsContNo = true;
        bool bNoOccued = false;

        try
        {
            var arry = strInsput.ToCharArray(0, strInsput.Length - 1);

            foreach (char item in arry)
            {
                if (char.IsNumber(item))
                {
                    strNumber = strNumber + item.ToString();

                    bIsContNo = true;

                    bNoOccued = true;
                }
                else
                {
                    bIsContNo = false;
                }

                if (bNoOccued && !bIsContNo)
                {
                    break;
                }


            }

            number = Convert.ToInt32(strNumber);

        }
        catch (Exception ex)
        {

            return 0;
        }

        return number;

    }
0
public static int GetFirstDigit(int n, bool removeSign = true) 
{
   if (removeSign)
      return n <= -10 || n >= 10 ? Math.Abs(n) % 10 : Math.Abs(n);
   else 
      return n <= -10 || n >= 10 ? n % 10 : n;
}

//Your code goes here
int[] test = new int[] { -1574, -221, 1246, -4, 8, 38546};
            
foreach(int n in test)                 
   Console.WriteLine(string.Format("{0} : {1}", n, GetFirstDigit(n)));

Output:

-1574 : 4

-221 : 1

1246 : 6

-4 : 4

8 : 8

38546 : 6

-2

Here is a simpler way that does not involve looping

int number = 1234
int firstDigit = Math.Floor(number/(Math.Pow(10, number.ToString().length - 1))

That would give us 1234/Math.Pow(10, 4 - 1) = 1234/1000 = 1

1
  • Cannot implicitly convert type 'double' to 'int'.
    – Younes
    Apr 22, 2009 at 11:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.