How to get the separate digits of an int number?

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

    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:

    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.

提交回复
热议问题