Return first digit of an integer

后端 未结 23 1829
醉梦人生
醉梦人生 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 13:51

    The missing recursive solution:

    int getFirstInt(int input) {
      if (input > 0 ? input < 10 : input > -10) {
        return input > 0 ? input : -input;
      }
      return getFirstInt(input / 10);
    }
    

    I wouldn't use the ternary operator in real life but - isn't it kind of beautiful? ;)

提交回复
热议问题