How to get the separate digits of an int number?

前端 未结 30 1902
陌清茗
陌清茗 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
    public int[] getDigitsOfANumber(int number) {
        String numStr = String.valueOf(number);
        int retArr[] = new int[numStr.length()];
    
        for (int i = 0; i < numStr.length(); i++) {
            char c = numStr.charAt(i);
            int digit = c;
            int zero = (char) '0';
            retArr[i] = digit - zero;
    
        }
        return retArr;
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 03:36

    Here is my answer, I did it for myself and I hope it's simple enough for those who don't want to use the String approach or need a more math-y solution:

    public static void reverseNumber2(int number) {
    
        int residual=0;
        residual=number%10;
        System.out.println(residual);
    
        while (residual!=number)  {
              number=(number-residual)/10;
              residual=number%10;
              System.out.println(residual);
        }
    }
    

    So I just get the units, print them out, substract them from the number, then divide that number by 10 - which is always without any floating stuff, since units are gone, repeat.

    0 讨论(0)
  • 2020-11-22 03:36

    neither chars() nor codePoints() — the other lambda

    String number = Integer.toString( 1100 );

    IntStream.range( 0, number.length() ).map( i -> Character.digit( number.codePointAt( i ), 10 ) ).toArray();  // [1, 1, 0, 0]
    
    0 讨论(0)
  • 2020-11-22 03:38

    Easier way I think is to convert the number to string and use substring to extract and then convert to integer.

    Something like this:

    int digits1 =Integer.parseInt( String.valueOf(201432014).substring(0,4));
        System.out.println("digits are: "+digits1);
    

    ouput is 2014

    0 讨论(0)
  • 2020-11-22 03:38

    Java 8 solution to get digits as int[] from an integer that you have as a String:

    int[] digits = intAsString.chars().map(i -> i - '0').toArray();
    
    0 讨论(0)
提交回复
热议问题