本文介紹了如何獲得整數的單獨數字?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有 1100、1002、1022 等數字.我想要單獨的數字,例如對于第一個數字 1100,我想要 1、1、0、0.
I have numbers like 1100, 1002, 1022 etc. I would like to have the individual digits, for example for the first number 1100 I want to have 1, 1, 0, 0.
如何在 Java 中獲得它?
How can I get it in Java?
推薦答案
為此,您將使用 %
(mod) 運算符.
To do this, you will use the %
(mod) operator.
int number; // = some int
while (number > 0) {
print( number % 10);
number = number / 10;
}
mod 運算符將為您提供對數字進行 int 除法的余數.
The mod operator will give you the remainder of doing int division on a number.
所以,
10012 % 10 = 2
因為:
10012 / 10 = 1001, remainder 2
注意: 正如 Paul 所說,這會以相反的順序為您提供數字.您需要將它們壓入堆棧并以相反的順序將它們彈出.
Note: As Paul noted, this will give you the numbers in reverse order. You will need to push them onto a stack and pop them off in reverse order.
按正確順序打印數字的代碼:
Code to print the numbers in the correct order:
int number; // = and int
LinkedList<Integer> stack = new LinkedList<Integer>();
while (number > 0) {
stack.push( number % 10 );
number = number / 10;
}
while (!stack.isEmpty()) {
print(stack.pop());
}
這篇關于如何獲得整數的單獨數字?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!