LoginSignup
12
8

More than 5 years have passed since last update.

Java:整数の桁数の求め方

Posted at

Androidで使おうと思ってすぐに分からなかったのでメモです。
すごく適当なので、間違いとか勘違いはご指摘いただければと思います。

  • 参考

http://hack.aipo.com/archives/4178/
http://d.hatena.ne.jp/kameid/20090313/1236957906

  1. BigDecimal.precision()

  2. String.length()

  3. Math.log10()

  4. Integer.stringSize

BigDecimal

BigDecimal.valueOf(x).precision();

String

String.valueOf(x).length();

Mathのlog10

Math.log10(x) + 1;

Integer

IntegerのtoStringで使ってるらしいですが、今は違うかも知れません(調べていなくてすみません)
定数と比較してたんですね。

final static int[] sizeTable = {
        9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE
};

// Requires positive x
static int stringSize(int x) {
    for (int i = 0;; i++)
        if (x <= sizeTable[i])
            return i + 1;
}

int digit = stringSize(x);

まとめ

どの方法でもあまり変わらないかと思いますが、コストはBigDecimalとStringを使う方法は毎回インスタンスを作るようなので、繰り返し違う値を求める場合はMathを使った方法がいいかもしれません。

12
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
8