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

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

    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;
    }
    

提交回复
热议问题