How to get the separate digits of an int number?

前端 未结 30 1930
陌清茗
陌清茗 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 03:14

    I think this will be the most useful way to get digits:

    public int[] getDigitsOf(int num)
    {        
        int digitCount = Integer.toString(num).length();
    
        if (num < 0) 
            digitCount--;           
    
        int[] result = new int[digitCount];
    
        while (digitCount-- >0) {
            result[digitCount] = num % 10;
            num /= 10;
        }        
        return result;
    }
    

    Then you can get digits in a simple way:

    int number = 12345;
    int[] digits = getDigitsOf(number);
    
    for (int i = 0; i < digits.length; i++) {
        System.out.println(digits[i]);
    }
    

    or more simply:

    int number = 12345;
    for (int i = 0; i < getDigitsOf(number).length; i++) {
        System.out.println(  getDigitsOf(number)[i]  );
    }
    

    Notice the last method calls getDigitsOf method too much time. So it will be slower. You should create an int array and then call the getDigitsOf method once, just like in second code block.

    In the following code, you can reverse to process. This code puts all digits together to make the number:

    public int digitsToInt(int[] digits)
    {
        int digitCount = digits.length;
        int result = 0;
    
        for (int i = 0; i < digitCount; i++) {
            result = result * 10;
            result += digits[i];
        }
    
        return result;
    }
    

    Both methods I have provided works for negative numbers too.

提交回复
热议问题