How to get the separate digits of an int number?

前端 未结 30 1984
陌清茗
陌清茗 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: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 digits = new ArrayList();
        collectDigits(num, digits);
        return digits.toArray(new Integer[]{});
    }
    
    private static void collectDigits(int num, List 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 digits = new ArrayList();
        collectDigits(num, digits);
        Collections.reverse(digits);
        return digits.toArray(new Integer[]{});
    }
    

提交回复
热议问题