有没有比这个方法更简洁的方法来获取整数的位数?
int numDigits = String.valueOf(1000).length();
有没有比这个方法更简洁的方法来获取整数的位数?
int numDigits = String.valueOf(1000).length();
当前回答
用设计(基于问题)。这是分治法的另一种。我们将首先定义一个枚举(考虑到它仅用于unsigned int)。
public enum IntegerLength {
One((byte)1,10),
Two((byte)2,100),
Three((byte)3,1000),
Four((byte)4,10000),
Five((byte)5,100000),
Six((byte)6,1000000),
Seven((byte)7,10000000),
Eight((byte)8,100000000),
Nine((byte)9,1000000000);
byte length;
int value;
IntegerLength(byte len,int value) {
this.length = len;
this.value = value;
}
public byte getLenght() {
return length;
}
public int getValue() {
return value;
}
}
现在我们将定义一个类,它遍历枚举的值,并比较并返回适当的长度。
public class IntegerLenght {
public static byte calculateIntLenght(int num) {
for(IntegerLength v : IntegerLength.values()) {
if(num < v.getValue()){
return v.getLenght();
}
}
return 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+"]");
}
由于以10为基数的整数的位数只是1 + truncate(log10(number)),您可以这样做:
public class Test {
public static void main(String[] args) {
final int number = 1234;
final int digits = 1 + (int)Math.floor(Math.log10(number));
System.out.println(digits);
}
}
被编辑是因为我的最后一次编辑修复了代码示例,但没有修复描述。
计算int变量中数字数的有效方法之一是定义一个方法digitsCounter,其中包含所需数量的条件语句。 方法很简单,我们将检查n位数字所在的每个范围: 0: 9为个位数 10:99是两位数 100: 999是三位数等等……
static int digitsCounter(int N)
{ // N = Math.abs(N); // if `N` is -ve
if (0 <= N && N <= 9) return 1;
if (10 <= N && N <= 99) return 2;
if (100 <= N && N <= 999) return 3;
if (1000 <= N && N <= 9999) return 4;
if (10000 <= N && N <= 99999) return 5;
if (100000 <= N && N <= 999999) return 6;
if (1000000 <= N && N <= 9999999) return 7;
if (10000000 <= N && N <= 99999999) return 8;
if (100000000 <= N && N <= 999999999) return 9;
return 10;
}
一种更干净的方法是取消下限检查,因为如果我们按顺序进行,就不需要下限检查了。
static int digitsCounter(int N)
{
N = N < 0 ? -N : N;
if (N <= 9) return 1;
if (N <= 99) return 2;
if (N <= 999) return 3;
if (N <= 9999) return 4;
if (N <= 99999) return 5;
if (N <= 999999) return 6;
if (N <= 9999999) return 7;
if (N <= 99999999) return 8;
if (N <= 999999999) return 9;
return 10; // Max possible digits in an 'int'
}
一个人想要这样做主要是因为他/她想要“呈现”它,这主要意味着它最终需要显式或隐式地“toString-ed”(或以另一种方式转换);才能呈现(例如打印出来)。如果是这种情况,那么只需尝试显式地使用必要的“toString”并计算位数。
那简单的数学呢?除以10,直到0。
public static int getSize(long number) {
int count = 0;
while (number > 0) {
count += 1;
number = (number / 10);
}
return count;
}