繁体   English   中英

将数字拆分为单独的数字算法的工作方式

[英]how a splitting number to a separate digits algorithm works

我回到软件开发领域,并且在Java中玩算法,今天我正在做算法,将数字拆分为单独的数字,我在这里找到了,我用Java编写了它。但说实话我不怎么 只是我不了解其中一部分的代码:

public static void main(String[] args) {
    Integer test = 0, i, N;
    ArrayList array_one= new ArrayList<Integer>();
    Scanner sc = new Scanner(System.in);

    System.out.print("Write An Integer :");
    test = sc.nextInt();
    while (test > 0){
      int mod = test % 10; // <= DON'T UNDERSTAND THE WORK OF THAT PART
                           // (i know it's the modulo of the entered value)
       test = test / 10;
       array_one.add(mod);
    }
    System.out.print(array_one);
}

我知道这是一个新手问题,我只是对软件工程和算法充满热情,只想提前知道它是如何工作的。

test % 10; 给您数字的最后一位(最低有效位),即数字除以10后的余数。

test = test / 10将数字减少一位数字(123456变为12345),从而使前第二个最低有效数字成为新的最低有效数字。 因此,在下一次迭代中, test % 10;否则, test % 10; 将返回第二个数字。

等等...

通过使用%10您将只获得最后一位数字。 /10将给出最后一位数字之前的数字。

这样就可以构造数组。

124%10 --> 4
124/10 --> 12   % 10 --> 2
             12 / 10 --> 1
test % 10;  --> Always gives you the last digit.
 test / 10; --> divides the existing number by 10.
 while loop --> executes until test > 0

So, if your number is 234,
234%10 would be 4
234/10 would be 23.4 which will be converted to 23.

Apply 23 % 10 and 23/10 and so on..

此处使用的逻辑是通过将数字除以10并获取提醒值来将单位位置分开。

例如x = 153

“%”是给出除法余数的模运算符“ /”是仅给出商的除法运算符

然后153%10 = 3 //这是分隔第一个数字的余数。 然后将数字除以10得到商

即153/10 = 15 //只有商

随着循环的进行,现在将15用作新的原始数字,并再次除以10以得到余数,从而得到下一个数字。

即15%10 = 5 //下一位15/10 = 1;

 1%10=1    //digit
 1/10=0   //The loop ends here

你可以通过一个例子来理解
您要除以数字的数字是345
如果将其除以10,您剩下的第一位数是5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM