How to get the separate digits of an int number?

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

    I wrote a program that demonstrates how to separate the digits of an integer using a more simple and understandable approach that does not involve arrays, recursions, and all that fancy schmancy. Here is my code:

    int year = sc.nextInt(), temp = year, count = 0;
    
    while (temp>0)
    {
      count++;
      temp = temp / 10;
    }
    
    double num = Math.pow(10, count-1);
    int i = (int)num;
    
    for (;i>0;i/=10)
    {
      System.out.println(year/i%10);
    }
    

    Suppose your input is the integer 123, the resulting output will be as follows:

    1
    2
    3
    

提交回复
热议问题