How can you get the first digit in an int (C#)?

后端 未结 25 2784
遇见更好的自我
遇见更好的自我 2020-12-02 05:43

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

25条回答
  •  抹茶落季
    2020-12-02 06:05

    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)
    

提交回复
热议问题