一般對(duì)于數(shù)字長(zhǎng)度的判斷,我們習(xí)慣上是采用模除的方法。
使用遞歸的思想得到結(jié)果。大智慧經(jīng)典版6.0下載
以下是jdk源碼中實(shí)現(xiàn)的思路:
-----------------------------------------------------------------------------------------
final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
static int stringSize(int x) {
for (int i=0; ; i++)
if (x <= sizeTable[i])
return i+1;
}
-----------------------------------------------------------------------------------------
遞歸實(shí)現(xiàn)的代碼:
int num = random.nextInt();
while (num / 10 > 0) {
num = num / 10;
length++;
}
------------------------------------------------
當(dāng)循環(huán)增加到百萬(wàn)數(shù)量級(jí)時(shí),
前者的時(shí)間差不多是后者數(shù)量級(jí)的一半 。