How to get the separate digits of an int number?

前端 未结 30 1963
陌清茗
陌清茗 2020-11-22 03:03

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.

How can I get

相关标签:
30条回答
  • 2020-11-22 03:11

    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:

    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. At the end you use toArray() method to change your stream into an int[] array.

    0 讨论(0)
  • 2020-11-22 03:13

    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 
    
    0 讨论(0)
  • 2020-11-22 03:14

    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.

    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.

    0 讨论(0)
  • 2020-11-22 03:14

    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()+ " ");
                    }
    
    0 讨论(0)
  • 2020-11-22 03:16

    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:

    /**
     * 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[]{});
    }
    
    0 讨论(0)
  • 2020-11-22 03:18

    Convert it to String and use String#toCharArray() or 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.

    IntStream chars = number.chars();
    
    0 讨论(0)
提交回复
热议问题