有没有比这个方法更简洁的方法来获取整数的位数?

int numDigits = String.valueOf(1000).length();

当前回答

我看到有人使用String库,甚至使用Integer类。这没什么问题,但是求位数的算法并不复杂。我在这个例子中使用的是long类型,但它也可以用于int类型。

 private static int getLength(long num) {

    int count = 1;

    while (num >= 10) {
        num = num / 10;
        count++;
    }

    return count;
}

其他回答

一个非常简单的解决方案:

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

或者相反,你可以检查这个数字是否大于或小于所需的数字。

    public void createCard(int cardNumber, int cardStatus, int customerId) throws SQLException {
    if(cardDao.checkIfCardExists(cardNumber) == false) {
        if(cardDao.createCard(cardNumber, cardStatus, customerId) == true) {
            System.out.println("Card created successfully");
        } else {

        }
    } else {
        System.out.println("Card already exists, try with another Card Number");
        do {
            System.out.println("Enter your new Card Number: ");
            scan = new Scanner(System.in);
            int inputCardNumber = scan.nextInt();
            cardNumber = inputCardNumber;
        } while(cardNumber < 95000000);
        cardDao.createCard(cardNumber, cardStatus, customerId);
    }
}

}

我在看了Integer.java源代码后写了这个函数。

private static int stringSize(int x) {
    final int[] sizeTable = {9, 99, 999, 9_999, 99_999, 999_999, 9_999_999,
            99_999_999, 999_999_999, Integer.MAX_VALUE};
    for (int i = 0; ; ++i) {
        if (x <= sizeTable[i]) {
            return i + 1;
        }
    }
}

下面是JDK开发人员给出的解决方案。JDK 17 (Long类):

/**
 * Returns the string representation size for a given long value.
 *
 * @param x long value
 * @return string size
 *
 * @implNote There are other ways to compute this: e.g. binary search,
 * but values are biased heavily towards zero, and therefore linear search
 * wins. The iteration results are also routinely inlined in the generated
 * code after loop unrolling.
 */
static int stringSize(long x) {
    int d = 1;
    if (x >= 0) {
        d = 0;
        x = -x;
    }
    long p = -10;
    for (int i = 1; i < 19; i++) {
        if (x > p)
            return i + d;
        p = 10 * p;
    }
    return 19 + d;
}

注意,如果需要的话,该方法会考虑减号。

不幸的是,该方法没有公开。

在性能方面,您可以从评论中看到,JDK开发人员与其他选项相比至少考虑了这一点。我猜 分而治之的方法倾向于较小的数字,效果会稍好一些 更好,因为CPU可以比整数更快地进行整数比较 乘法。但这种差异可能小到无法测量。

无论如何,我希望JDK中已经公开了这个方法,这样人们就不会开始使用自己的方法了。

另一种字符串方法。简单明了,对于任意整数n。

int length = ("" + n).length();