Home > Mobile >  How to get the digits of an integer and store it into an array? [Java]
How to get the digits of an integer and store it into an array? [Java]

Time:12-17

I'm pretty new to programming, found this interesting problem in Programming Praxis and got stuck at how to get the digits of an integer and storing them into an array.

I honestly do not know where to start and I'd like to learn how to do this in Java

If you're interested, this is the code on the problem I'm working on.

public class MyClass {
    public static void main(String args[]) {
    // Determine all three-digit numbers N having the property that N is divisible by 11, and N/11 is equal to the sum of the squares of the digits of N.
    int num = 100;
    int square_sum = 0;
    int digit1 = 0;
    int digit2 = 0;
    int digit3 = 0;
    while (num <= 999){
        
        if (num % 11 == 0) { //if remainder == 0; the number is divisible by 11// 
           
            // We need to get the digits of int "num" and square them // 
            int arrayDigits[] = new int[3];

            } else 
                num  ;
        }
    }
}

CodePudding user response:

Here is an example: (doesn't match with your code so you have to think about it a bit)

 int[] arr = new int[] {100, 123, 21};

//get first index of your array
        int a = arr[0];

//turn it into a string
        String b = String.valueOf(a);

//split the string
        String[] c = b.split("");

        System.out.println(c[0]);

With this way your String[] c is a string array and you can access the values just like a normal array

CodePudding user response:

public static void main(String args[]) {
    // Determine all three-digit numbers N having the property that N is divisible by 11, and N/11 is equal to the sum of the squares of the digits of N.
    int num = 100;
    int square_sum = 0;
    int digit1 = 0;
    int digit2 = 0;
    int digit3 = 0;
    while (num <= 999) {
        if (num % 11 == 0) { //if remainder == 0; the number is divisible by 11//
            // We need to get the digits of int "num" and square them //
            int arrayDigits[] = new int[3];
            digit1 = num % 10;
            digit2 = (num / 10) % 10;
            digit3 = (num / 100) % 10;
            square_sum = digit1 * digit1   digit2 * digit2   digit3 * digit3;
            if ((num / 11) == square_sum) {
                System.out.println(num);
            }
        }
        num  ;
    }
}

If you wanna get each digits of int "num"

digit1 = num % 10;
digit2 = (num / 10) % 10;
digit3 = (num / 100) % 10;
  • Related