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

后端 未结 25 2782
遇见更好的自我
遇见更好的自我 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 05:47

    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.

提交回复
热议问题