Way to get number of digits in an int?

后端 未结 30 1356
梦毁少年i
梦毁少年i 2020-11-22 17:21

Is there a neater way for getting the number of digits in an int than this method?

int numDigits = String.valueOf(1000).length();
30条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 17:36

    A really simple solution:

    public int numLength(int n) {
      for (int length = 1; n % Math.pow(10, length) != n; length++) {}
      return length;
    }
    

提交回复
热议问题