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

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

当前回答

这是我做的一个非常简单的方法,适用于任何数字:

public static int numberLength(int userNumber) {

    int numberCounter = 10;
    boolean condition = true;
    int digitLength = 1;

    while (condition) {
        int numberRatio = userNumber / numberCounter;
        if (numberRatio < 1) {
            condition = false;
        } else {
            digitLength++;
            numberCounter *= 10;
        }
    }

    return digitLength; 
}

它的工作方式是使用数字计数器变量,即10 = 1位空格。例如。1 = 1十分之一=> 1位空格。因此,如果你有int number = 103342;你会得到6,因为这相当于。000001个空格。还有,谁有更好的numberCounter变量名?我想不出比这更好的了。

编辑:我想到了一个更好的解释。本质上,这个while循环所做的就是让你的数字除以10,直到它小于1。从本质上讲,当你将一个数除以10时,你是在向后移动一个数字空间,所以你只需将它除以10,直到你的数字中的位数小于1。

下面是另一个版本,可以计算小数中的数字数量:

public static int repeatingLength(double decimalNumber) {

    int numberCounter = 1;
    boolean condition = true;
    int digitLength = 1;

    while (condition) {
        double numberRatio = decimalNumber * numberCounter;

        if ((numberRatio - Math.round(numberRatio)) < 0.0000001) {
            condition = false;
        } else {
            digitLength++;
            numberCounter *= 10;
        }
    }
    return digitLength - 1;
}

其他回答

我们可以使用递归循环来实现这一点

    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+"]");
    }

我能试试吗?;)

基于德克的解决方案

final int digits = number==0?1:(1 + (int)Math.floor(Math.log10(Math.abs(number))));

现在还不能留言,所以我会单独回复。

基于对数的解决方案不能计算非常大的长整数的正确位数,例如:

long n = 99999999999999999L;

// correct answer: 17
int numberOfDigits = String.valueOf(n).length();

// incorrect answer: 18
int wrongNumberOfDigits = (int) (Math.log10(n) + 1); 

基于对数的解决方案在大整数中计算不正确的位数

一个人想要这样做主要是因为他/她想要“呈现”它,这主要意味着它最终需要显式或隐式地“toString-ed”(或以另一种方式转换);才能呈现(例如打印出来)。如果是这种情况,那么只需尝试显式地使用必要的“toString”并计算位数。

使用Java

int nDigits = Math.floor(Math.log10(Math.abs(the_integer))) + 1;

使用import java.lang.Math.*;一开始

使用C

int nDigits = floor(log10(abs(the_integer))) + 1;

在开始时使用include math.h