How to get the separate digits of an int number?

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

    To do this, you will use the % (mod) operator.

    int number; // = some int
    
    while (number > 0) {
        print( number % 10);
        number = number / 10;
    }
    

    The mod operator will give you the remainder of doing int division on a number.

    So,

    10012 % 10 = 2
    

    Because:

    10012 / 10 = 1001, remainder 2
    

    Note: As Paul noted, this will give you the numbers in reverse order. You will need to push them onto a stack and pop them off in reverse order.

    Code to print the numbers in the correct order:

    int number; // = and int
    LinkedList stack = new LinkedList();
    while (number > 0) {
        stack.push( number % 10 );
        number = number / 10;
    }
    
    while (!stack.isEmpty()) {
        print(stack.pop());
    }
    

提交回复
热议问题