Java 如何获得一个int数字的单独数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3389264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the separate digits of an int number?
提问by Edy Moore
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.
我有 1100、1002、1022 等数字。我想要单独的数字,例如对于第一个数字 1100,我想要 1、1、0、0。
How can I get it in Java?
我怎样才能在Java中获得它?
回答by BalusC
Convert it to String
and use String#toCharArray()
or String#split()
.
将其转换为String
并使用String#toCharArray()
或String#split()
。
String number = String.valueOf(someInt);
char[] digits1 = number.toCharArray();
// or:
String[] digits2 = number.split("(?<=.)");
In case you're already on Java 8 and you happen to want to do some aggregate operations on it afterwards, consider using String#chars()
to get an IntStream
out of it.
如果您已经在使用 Java 8 并且以后碰巧想对其进行一些聚合操作,请考虑使用它String#chars()
来摆脱IntStream
它。
IntStream chars = number.chars();
回答by jjnguy
To do this, you will use the %
(mod) operator.
为此,您将使用%
(mod) 运算符。
int number; // = some int
while (number > 0) {
print( number % 10);
number = number / 10;
}
The mod operator will give you the remainder of doing int division on a number.
mod 运算符将为您提供对数字进行 int 除法的剩余部分。
So,
所以,
10012 % 10 = 2
Because:
因为:
10012 / 10 = 1001, remainder 2
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());
}
回答by Don Branson
Integer.toString(1100)gives you the integer as a string. Integer.toString(1100).getBytes()to get an array of bytes of the individual digits.
Integer.toString(1100)为您提供字符串形式的整数。 Integer.toString(1100).getBytes()获取单个数字的字节数组。
Edit:
编辑:
You can convert the character digits into numeric digits, thus:
您可以将字符数字转换为数字数字,因此:
String string = Integer.toString(1234);
int[] digits = new int[string.length()];
for(int i = 0; i<string.length(); ++i){
digits[i] = Integer.parseInt(string.substring(i, i+1));
}
System.out.println("digits:" + Arrays.toString(digits));
回答by Marimuthu Madasamy
How about this?
这个怎么样?
public static void printDigits(int num) {
if(num / 10 > 0) {
printDigits(num / 10);
}
System.out.printf("%d ", num % 10);
}
or instead of printing to the console, we can collect it in an array of integers and then print the array:
或者不打印到控制台,我们可以将它收集在一个整数数组中,然后打印该数组:
public static void main(String[] args) {
Integer[] digits = getDigits(12345);
System.out.println(Arrays.toString(digits));
}
public static Integer[] getDigits(int num) {
List<Integer> digits = new ArrayList<Integer>();
collectDigits(num, digits);
return digits.toArray(new Integer[]{});
}
private static void collectDigits(int num, List<Integer> digits) {
if(num / 10 > 0) {
collectDigits(num / 10, digits);
}
digits.add(num % 10);
}
If you would like to maintain the order of the digits from least significant (index[0]) to most significant (index[n]), the following updated getDigits() is what you need:
如果您想保持从最不重要 (index[0]) 到最重要 (index[n]) 的数字顺序,则需要以下更新的 getDigits():
/**
* split an integer into its individual digits
* NOTE: digits order is maintained - i.e. Least significant digit is at index[0]
* @param num positive integer
* @return array of digits
*/
public static Integer[] getDigits(int num) {
if (num < 0) { return new Integer[0]; }
List<Integer> digits = new ArrayList<Integer>();
collectDigits(num, digits);
Collections.reverse(digits);
return digits.toArray(new Integer[]{});
}
回答by Ramazan Polat
I think this will be the most useful way to get digits:
我认为这将是获得数字的最有用的方法:
public int[] getDigitsOf(int num)
{
int digitCount = Integer.toString(num).length();
if (num < 0)
digitCount--;
int[] result = new int[digitCount];
while (digitCount-- >0) {
result[digitCount] = num % 10;
num /= 10;
}
return result;
}
Then you can get digits in a simple way:
然后您可以通过简单的方式获取数字:
int number = 12345;
int[] digits = getDigitsOf(number);
for (int i = 0; i < digits.length; i++) {
System.out.println(digits[i]);
}
or more simply:
或更简单地说:
int number = 12345;
for (int i = 0; i < getDigitsOf(number).length; i++) {
System.out.println( getDigitsOf(number)[i] );
}
Notice the last method calls getDigitsOf method too much time. So it will be slower. You should create an int array and then call the getDigitsOf method once, just like in second code block.
注意最后一个方法调用 getDigitsOf 方法的时间太长了。所以会比较慢。您应该创建一个 int 数组,然后调用一次 getDigitsOf 方法,就像在第二个代码块中一样。
In the following code, you can reverse to process. This code puts all digits together to make the number:
在下面的代码中,您可以反向处理。此代码将所有数字放在一起以形成数字:
public int digitsToInt(int[] digits)
{
int digitCount = digits.length;
int result = 0;
for (int i = 0; i < digitCount; i++) {
result = result * 10;
result += digits[i];
}
return result;
}
Both methods I have provided works for negative numbers too.
我提供的两种方法也适用于负数。
回答by Jonathan Norman
// could be any num this is a randomly generated one
int num = (int) (Math.random() * 1000);
// this will return each number to a int variable
int num1 = num % 10;
int num2 = num / 10 % 10;
int num3 = num /100 % 10;
// you could continue this pattern for 4,5,6 digit numbers
// dont need to print you could then use the new int values man other ways
System.out.print(num1);
System.out.print("\n" + num2);
System.out.print("\n" + num3);
回答by Simple Sandman
This uses the modulo 10 method to figure out each digit in a number greater than 0, then this will reverse the order of the array. This is assuming you are not using "0" as a starting digit.
这使用模 10 方法来计算大于 0 的数字中的每个数字,然后这将反转数组的顺序。这是假设您没有使用“0”作为起始数字。
This is modified to take in user input.
This array is originally inserted backwards, so I had to use the Collections.reverse()
call to put it back into the user's order.
这被修改为接受用户输入。这个数组最初是向后插入的,所以我不得不使用Collections.reverse()
调用将它放回用户的订单中。
Scanner scanNumber = new Scanner(System.in);
int userNum = scanNumber.nextInt(); // user's number
// divides each digit into its own element within an array
List<Integer> checkUserNum = new ArrayList<Integer>();
while(userNum > 0) {
checkUserNum.add(userNum % 10);
userNum /= 10;
}
Collections.reverse(checkUserNum); // reverses the order of the array
System.out.print(checkUserNum);
回答by espiering
I haven't seen anybody use this method, but it worked for me and is short and sweet:
我还没有看到有人使用这种方法,但它对我有用,而且简短而甜蜜:
int num = 5542;
String number = String.valueOf(num);
for(int i = 0; i < number.length(); i++) {
int j = Character.digit(number.charAt(i), 10);
System.out.println("digit: " + j);
}
This will output:
这将输出:
digit: 5
digit: 5
digit: 4
digit: 2
回答by Dushyant
int number = 12344444; // or it Could be any valid number
int temp = 0;
int divider = 1;
for(int i =1; i< String.valueOf(number).length();i++)
{
divider = divider * 10;
}
while (divider >0) {
temp = number / divider;
number = number % divider;
System.out.print(temp +" ");
divider = divider/10;
}
回答by Forever Alone
I wrote a program that demonstrates how to separate the digits of an integer using a more simple and understandable approach that does not involve arrays, recursions, and all that fancy schmancy. Here is my code:
我编写了一个程序,它演示了如何使用更简单易懂的方法来分隔整数的数字,该方法不涉及数组、递归和所有那些花哨的技巧。这是我的代码:
int year = sc.nextInt(), temp = year, count = 0;
while (temp>0)
{
count++;
temp = temp / 10;
}
double num = Math.pow(10, count-1);
int i = (int)num;
for (;i>0;i/=10)
{
System.out.println(year/i%10);
}
Suppose your input is the integer 123
, the resulting output will be as follows:
假设您的输入是 integer 123
,结果输出将如下所示:
1
2
3