简体   繁体   English

如何获得一个int数字的单独数字?

[英]How to get the separate digits of an int number?

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中获得它?

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());
}

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();

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[]{});
}

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

I noticed that there are few example of using Java 8 stream to solve your problem but I think that this is the simplest one:我注意到使用 Java 8 流解决您的问题的示例很少,但我认为这是最简单的示例:

int[] intTab = String.valueOf(number).chars().map(Character::getNumericValue).toArray();

To be clear: You use String.valueOf(number) to convert int to String, then chars() method to get an IntStream (each char from your string is now an Ascii number), then you need to run map() method to get a numeric values of the Ascii number.需要明确的是:您使用String.valueOf(number)将 int 转换为 String,然后使用chars()方法获取 IntStream(您的字符串中的每个字符现在都是一个 Ascii 数),然后您需要运行map()方法来获取 Ascii 数的数值。 At the end you use toArray() method to change your stream into an int[] array.最后,您使用toArray()方法将流更改为 int[] 数组。

I see all the answer are ugly and not very clean.我看到所有的答案都很丑陋而且不是很干净。

I suggest you use a little bit of recursion to solve your problem.我建议你使用一点递归来解决你的问题。 This post is very old, but it might be helpful to future coders.这篇文章很旧,但它可能对未来的编码人员有所帮助。

public static void recursion(int number) {
    if(number > 0) {
        recursion(number/10);
        System.out.printf("%d   ", (number%10));
    }
}

Output:输出:

Input: 12345

Output: 1   2   3   4   5 

simple solution简单的解决方案

public static void main(String[] args) {
    int v = 12345;
    while (v > 0){
        System.out.println(v % 10);
        v /= 10;
    }
}
// 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);

Since I don't see a method on this question which uses Java 8, I'll throw this in. Assuming that you're starting with a String and want to get a List<Integer> , then you can stream the elements like so.由于我在这个问题上没有看到使用 Java 8 的方法,我将把它扔进去。假设你从一个String开始并且想要一个List<Integer> ,那么你可以像这样流式传输元素.

List<Integer> digits = digitsInString.chars()
        .map(Character::getNumericValue)
        .boxed()
        .collect(Collectors.toList());

This gets the characters in the String as a IntStream , maps those integer representations of characters to a numeric value, boxes them, and then collects them into a list.这将获取String中的String作为IntStream ,将这些字符的整数表示映射到一个数值,将它们装箱,然后将它们收集到一个列表中。

Easier way I think is to convert the number to string and use substring to extract and then convert to integer.我认为更简单的方法是将数字转换为字符串并使用substring提取然后转换为整数。

Something like this:像这样的东西:

int digits1 =Integer.parseInt( String.valueOf(201432014).substring(0,4));
    System.out.println("digits are: "+digits1);

ouput is 2014输出是 2014

Java 9 introduced a new Stream.iterate method which can be used to generate a stream and stop at a certain condition. Java 9 引入了一个新的Stream.iterate方法,可用于生成流并在特定条件下停止。 This can be used to get all the digits in the number, using the modulo approach.这可用于使用模方法获取数字中的所有数字。

int[] a = IntStream.iterate(123400, i -> i > 0, i -> i / 10).map(i -> i % 10).toArray();

Note that this will get the digits in reverse order, but that can be solved either by looping through the array backwards (sadly reversing an array is not that simple ), or by creating another stream:请注意,这将以相反的顺序获取数字,但这可以通过向后循环数组来解决(遗憾的是反转数组并不是那么简单),或者通过创建另一个流:

int[] b = IntStream.iterate(a.length - 1, i -> i >= 0, i -> i - 1).map(i -> a[i]).toArray();

or或者

int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length - i]).toArray();

As an example, this code:例如,此代码:

int[] a = IntStream.iterate(123400, i -> i > 0, i -> i / 10).map(i -> i % 10).toArray();
int[] b = IntStream.iterate(a.length - 1, i -> i >= 0, i -> i - 1).map(i -> a[i]).toArray();
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));

Will print:将打印:

[0, 0, 4, 3, 2, 1]
[1, 2, 3, 4, 0, 0]

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:假设您的输入是整数123 ,结果输出如下:

1
2
3

Here is my answer, I did it for myself and I hope it's simple enough for those who don't want to use the String approach or need a more math-y solution:这是我的答案,我是为自己做的,我希望它对于那些不想使用 String 方法或需要更多数学解决方案的人来说足够简单:

public static void reverseNumber2(int number) {

    int residual=0;
    residual=number%10;
    System.out.println(residual);

    while (residual!=number)  {
          number=(number-residual)/10;
          residual=number%10;
          System.out.println(residual);
    }
}

So I just get the units, print them out, substract them from the number, then divide that number by 10 - which is always without any floating stuff, since units are gone, repeat.所以我只是得到单位,打印出来,从数字中减去它们,然后将该数字除以 10 - 这总是没有任何浮动的东西,因为单位消失了,重复。

Why don't you do:你为什么不这样做:

String number = String.valueOf(input);
char[] digits = number.toCharArray();

Java 8 解决方案,用于从作为字符串的整数获取数字为 int[]:

int[] digits = intAsString.chars().map(i -> i - '0').toArray();

chars()codePoints()都不是——另一个 lambda

String number = Integer.toString( 1100 );

IntStream.range( 0, number.length() ).map( i -> Character.digit( number.codePointAt( i ), 10 ) ).toArray();  // [1, 1, 0, 0]

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.这使用模 10 方法来计算大于 0 的数字中的每个数字,然后这将反转数组的顺序。 This is assuming you are not using "0" as a starting digit.这是假设您没有使用“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);
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;
}

Just to build on the subject, here's how to confirm that the number is a palindromic integer in Java:只是为了建立这个主题,这里是如何确认该数字是 Java 中的回文整数:

public static boolean isPalindrome(int input) {
List<Integer> intArr = new ArrayList();
int procInt = input;

int i = 0;
while(procInt > 0) {
    intArr.add(procInt%10);
    procInt = procInt/10;
    i++;
}

int y = 0;
int tmp = 0;
int count = 0;
for(int j:intArr) {
    if(j == 0 && count == 0) {
    break;
    }

    tmp = j + (tmp*10);
    count++;
}

if(input != tmp)
    return false;

return true;
}

I'm sure I can simplify this algo further.我相信我可以进一步简化这个算法。 Yet, this is where I am.然而,这就是我所在的地方。 And it has worked under all of my test cases.它适用于我所有的测试用例。

I hope this helps someone.我希望这可以帮助别人。

Try this:尝试这个:

int num= 4321
int first  =  num % 10;
int second =  ( num - first ) % 100 / 10;
int third  =  ( num - first - second ) % 1000 / 100;
int fourth =  ( num - first - second - third ) % 10000 / 1000;

You will get first = 1, second = 2, third = 3 and fourth = 4 ....你会得到第一个 = 1,第二个 = 2,第三个 = 3 和第四个 = 4 ....

Integer.toString(1100) gives you the integer as a string. Integer.toString(1100)为您提供字符串形式的整数。 Integer.toString(1100).getBytes() to get an array of bytes of the individual digits. 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));
public int[] getDigitsOfANumber(int number) {
    String numStr = String.valueOf(number);
    int retArr[] = new int[numStr.length()];

    for (int i = 0; i < numStr.length(); i++) {
        char c = numStr.charAt(i);
        int digit = c;
        int zero = (char) '0';
        retArr[i] = digit - zero;

    }
    return retArr;
}

Something like this will return the char[] :这样的事情将返回char[]

public static char[] getTheDigits(int value){
    String str = "";
    int number = value;
    int digit = 0;
    while(number>0){
        digit = number%10;
        str = str + digit;
        System.out.println("Digit:" + digit);
        number = number/10;     

    }
    return str.toCharArray();
}

As a noob, my answer would be:作为菜鸟,我的回答是:

String number = String.valueOf(ScannerObjectName.nextInt()); 
int[] digits = new int[number.length()]; 
for (int i = 0 ; i < number.length() ; i++)
    int[i] = Integer.parseInt(digits.substring(i,i+1))

Now all the digits are contained in the "digits" array.现在所有的数字都包含在“digits”数组中。

if digit is meant to be a Character如果数字是一个Character

String numstr = Integer.toString( 123 );
Pattern.compile( "" ).splitAsStream( numstr ).map(
  s -> s.charAt( 0 ) ).toArray( Character[]::new );  // [1, 2, 3]

and the following works correctly并且以下工作正常
numstr = "000123" gets [0, 0, 0, 1, 2, 3] numstr = "000123"得到[0, 0, 0, 1, 2, 3]
numstr = "-123" gets [-, 1, 2, 3] numstr = "-123"得到[-, 1, 2, 3]

Try this one.试试这个。

const check = (num) => {
  let temp = num
  let result = []
  while(temp > 0){
    let a = temp%10;
    result.push(a);
    temp = (temp-a)/10;
  }
  return result;
}

check(98) //[ 8, 9 ]

使用 LINQ 的 .NET 解决方案。

List<int> numbers = number.ToString().Select(x => x - 48).ToList();

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.注意最后一个方法调用 getDigitsOf 方法的时间太长了。 So it will be slower.所以会比较慢。 You should create an int array and then call the getDigitsOf method once, just like in second code block.您应该创建一个 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.我提供的两种方法也适用于负数。

see bellow my proposal with comments见下面我的建议和评论

          int size=i.toString().length(); // the length of the integer (i) we need to split;
           ArrayList<Integer> li = new ArrayList<Integer>(); // an ArrayList in whcih to store the resulting digits

        Boolean b=true; // control variable for the loop in which we will reatrive step by step the digits
        String number="1"; // here we will add the leading zero depending on the size of i
        int temp;  // the resulting digit will be kept by this temp variable

    for (int j=0; j<size; j++){
                        number=number.concat("0");
                    }

Integer multi = Integer.valueOf(number); // the variable used for dividing step by step the number we received 
                while(b){

                    multi=multi/10;
                    temp=i/(multi);
                    li.add(temp);
                    i=i%(multi);
                                        if(i==0){
                                        b=false;
                                        }


                }

                for(Integer in: li){
                    System.out.print(in.intValue()+ " ");
                }
import java.util.Scanner;

class  Test 
{  
    public static void main(String[] args)   
    {  
        Scanner sc = new Scanner(System.in); 


    int num=sc.nextInt(); 
    System.out.println("Enter a number (-1 to end):"+num);
    int result=0;
    int i=0;
    while(true) 
    { 
      int n=num%10;
      if(n==-1){
        break;
      }
      i++;
      System.out.println("Digit"+i+" = "+n);
      result=result*10+n;
      num=num/10; 


      if(num==0) 
      { 
        break; 
      } 
    }
    }
}

in Java, this is how you can separate digits from numbers and store them in an Array. 在Java中,这是将数字与数字分开并将其存储在数组中的方式。

public static void main(String[] args) {
        System.out.println("Digits Array:: "+Arrays.toString(getNumberArr(1100)));
}

private static Integer[] getNumberArr(int number) {
    //will get the total number of digits in the number
    int temp = number;
    int counter = 0;

    while (temp > 0) {
        temp /= 10;
        counter++;
    }
    //reset the temp
    temp = number;

    // make an array
    int modulo;     //modulo is equivalent to single digit of the number.
    Integer[] numberArr = new Integer[counter];
    for (int i = counter - 1; i >= 0; i--) {
        modulo = temp % 10;
        numberArr[i] = modulo;  
        temp /= 10;
    }

    return numberArr;
}

Output: 输出:

Digits Array:: [1, 1, 0, 0]
import java.util.Scanner;

public class SeparatingDigits {

    public static void main( String[] args )
    {

        System.out.print( "Enter the digit to print separately :- ");
        Scanner scan = new Scanner( System.in );

        int element1 = scan.nextInt();
        int divider;

        if( ( element1 > 9999 ) && ( element1 <= 99999 ) )
        {
            divider = 10000;
        }
        else if( ( element1 > 999 ) && ( element1 <= 9999 ) )
        {
            divider = 1000;
        }
        else if ( ( element1 > 99) && ( element1 <= 999 ) )
        {
            divider = 100;
        }
        else if( ( element1 > 9 ) && ( element1 <= 99 ) )
        {
            divider = 10;
        }
        else 
        {
            divider = 1;
        }

        quotientFinder( element1, divider );




    }

     public static void quotientFinder( int elementValue, int dividerValue )
     {
         for( int count = 1;  dividerValue != 0; count++)
         {
            int quotientValue = elementValue / dividerValue ;
            elementValue = elementValue % dividerValue ;
            System.out.printf( "%d  ", quotientValue );

            dividerValue /= 10;

         }
     }
    }

Without using arrays and Strings . 不使用数组和字符串。 ( digits 1-99999 ) (数字1-99999)

output : 输出:

Enter the digit to print separately :- 12345 输入要单独打印的数字:-12345

1 2 3 4 5 1 2 3 4 5

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

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