在Java中,如果不使用String,如何从左边截断数字



我想知道是否有人知道如何使用数学从左边截断数字(从左边开始逐个删除数字)。

我可以用一个简单的除法来截断右边的数字:

int num = 10098;
while (num > 0){
    System.out.println(num);
    num /= 10;
}

这将输出我想要的:

10098
1009
100
10
1

但是,有人知道用另一种方法来处理整数,并在不转换为字符串的情况下截断左边的数字吗?

尝试n = n % (int) Math.pow(10, (int) Math.log10(n));。在这里找到。

public void test() {
    int n = 10098;
    while (n > 0) {
        System.out.println("n=" + n);
        n = n % (int) Math.pow(10, (int) Math.log10(n));
    }
}

打印

n=10098
n=98
n=8
int in = ...;
//the first number n : 10^n > in 
int mostSignificantDigit = 1;
int digits = 1;
while(mostSignificantDigit < in)
{
     mostSignificantDigit *= 10;
     digits++;
}
//create the numbers
int[] result = new int[digits];
int count = 0;
while(mostSignificantDigit != 0){
     result[count] = in % mostSignificantDigit;
     mostSignificantDigit /= 10;
}

您可以使用模块操作%。模块是除法的余数。

你必须用10的幂来称呼它。所以10、100、1000、10000

你可以做到

int num = 10098;
int divided = num;
int module = 1;
while (divided > 0) {
    divided /= 10;
    module *= 10;
    System.out.println(num % module);    
}

请注意,如果您不在填充处留下零,您将获得98,而不是0098或098。

最新更新