How to get the separate digits of an int number?

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

    // could be any num this is a randomly generated one
    int num = (int) (Math.random() * 1000);
    
    // this will return each number to a int variable
    int num1 = num % 10;
    int num2 = num / 10 % 10;
    int num3 = num /100 % 10;
    
    // you could continue this pattern for 4,5,6 digit numbers
    // dont need to print you could then use the new int values man other ways
    System.out.print(num1);
    System.out.print("\n" + num2);
    System.out.print("\n" + num3);
    

提交回复
热议问题