Return first digit of an integer

后端 未结 23 1837
醉梦人生
醉梦人生 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:10

    Yet another way:

    public int firstDigit(int x) {
      if (x == 0) return 0;
      x = Math.abs(x);
      return (int) Math.floor(x / Math.pow(10, Math.floor(Math.log10(x))));
    }
    

提交回复
热议问题