How to get the separate digits of an int number?

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

    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
    

提交回复
热议问题