How to get the separate digits of an int number?

前端 未结 30 2333
陌清茗
陌清茗 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:34

    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.

    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.

        Scanner scanNumber = new Scanner(System.in);
        int userNum = scanNumber.nextInt(); // user's number
    
        // divides each digit into its own element within an array
        List checkUserNum = new ArrayList();
        while(userNum > 0) {
            checkUserNum.add(userNum % 10);
            userNum /= 10;
        }
    
        Collections.reverse(checkUserNum); // reverses the order of the array
    
        System.out.print(checkUserNum);
    

提交回复
热议问题