[英]Java Split Number into Digit's Algorithm
package test;
import java.util.Scanner;
public class SplitNumber
{
public static void main(String[] args)
{
int num, temp, factor = 1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
num = sc.nextInt();
temp = num;
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
System.out.print("Each digits of given number are: ");
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
}
}
我無法理解這個因素的工作。 有人可以幫我理解這個代碼算法嗎?
模數運算符從數字中提取最右邊的數字。 例如,x%10產生x的最右邊數字(以10為底)。 類似地,x%100產生最后兩位數。
在編程語言中,如果您將int保留為double值,則將數字四舍五入為小數,因此,如果您執行15/10,則將返回1作為int;如果執行5/10,則將返回0。使用此知識,您可以了解。
例如,將數字設為953,
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
1.迭代溫度= 95,因子= 10
2.迭代溫度= 9,因子= 100
3,迭代溫度= 0,因子= 1000
while循環結束因為temp為0。
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
1.Iteration num = 953 factor = 100,953 / 100 = 9(你得到第一個數字)
2.迭代數 = 953%100 = 53,因子= 10,53/ 10 = 5(得到第二位數字)
3.Iteration num = 53%10 = 3,factor = 1,3 / 1 = 3(你得到最后一位數)
while循環結束。
其實這是基礎數學。 當要提取數字的第n個數字時,只需將其除以10 ^ n。
如果你不關心翻轉數字的順序,你可以簡單地寫
int num = sc.nextInt();
do {
System.out.println(num % 10);
num = num / 10;
} while(num != 0);
在模運算 num % 10
計算分割的其余部分num
通過10
,有效地獲取數字在最低位置(“一”)。 0 % 10
為0
... 9 % 10
為9
10 % 10
再次為0
,依此類推。 然后除以10
使舊“十”成為新的“一”,整個事情重復直到0
為止。
您的代碼中的麻煩是以“正確”順序發出數字,首先是最高位置,最后是最后位置。 因此,它首先檢查您的數字中有多少位數, factor
在此過程中增長到相同的大小。 temp=temp/10;
具有與num=num/10;
相同的作用num=num/10;
在短期片段(切割從在每個迭代的數量的數字),以及factor=factor*10
“增加了”一個數字到factor
在同一時間。 [我只是在這里停下來,因為已經有一個可以解釋這個問題的答案]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.