Return first digit of an integer

后端 未结 23 1787
醉梦人生
醉梦人生 2020-11-28 13:12

How in Java do you return the first digit of an integer.?

i.e.

345

Returns an int of 3.

23条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 14:09

    public static int firstDigit(int n) {
      while (n < -9 || 9 < n) n /= 10;
      return Math.abs(n);
    }
    

    Should handle negative numbers pretty well, too. Will return a negative first digit in that case.

提交回复
热议问题