有没有比这个方法更简洁的方法来获取整数的位数?
int numDigits = String.valueOf(1000).length();
有没有比这个方法更简洁的方法来获取整数的位数?
int numDigits = String.valueOf(1000).length();
当前回答
下面是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中已经公开了这个方法,这样人们就不会开始使用自己的方法了。
其他回答
或者相反,你可以检查这个数字是否大于或小于所需的数字。
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);
}
}
}
现在还不能留言,所以我会单独回复。
基于对数的解决方案不能计算非常大的长整数的正确位数,例如:
long n = 99999999999999999L;
// correct answer: 17
int numberOfDigits = String.valueOf(n).length();
// incorrect answer: 18
int wrongNumberOfDigits = (int) (Math.log10(n) + 1);
基于对数的解决方案在大整数中计算不正确的位数
一个非常简单的解决方案:
public int numLength(int n) {
for (int length = 1; n % Math.pow(10, length) != n; length++) {}
return length;
}
对数是你的朋友:
int n = 1000;
int length = (int)(Math.log10(n)+1);
NB:只对n >有效0。
我们可以使用递归循环来实现这一点
public static int digitCount(int numberInput, int i) {
while (numberInput > 0) {
i++;
numberInput = numberInput / 10;
digitCount(numberInput, i);
}
return i;
}
public static void printString() {
int numberInput = 1234567;
int digitCount = digitCount(numberInput, 0);
System.out.println("Count of digit in ["+numberInput+"] is ["+digitCount+"]");
}