簡體   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