Search code examples
javamodulomodulus

How to sort numbers in Android Studio?


How do I put each number in a variable, for example, I have 2118 and I want this:

How do I do this if the number is unknown?

int abcd = 2118;
int a = 8;
int b = 10;
int c = 100;
int d = 2000;

Or

int abcd = 2118;
int a = 8; // 8
int b = 1; // 10
int c = 1; // 100
int d = 2; //2000

Solution

  • I would use the modulus operator to do what (I think) you are asking.

    Something like this...

     int num=1351280;
     int ones = (num % 10)/1;
     int tens = (num-ones) % 100;
     int hun = (num-(tens+ones)) % 1000;
     int thou = (num-(tens+ones+hun)) % 10000;
     int tenThou = (num-(tens+ones+hun+thou)) % 100000;
     int hunThou = (num-(tens+ones+hun+thou+tenThou)) % 1000000;
     int mil  = (num-(tens+ones+hun+thou+tenThou+hunThou)) % 10000000;
    
     System.out.println(mil);
     System.out.println(hunThou);
     System.out.println(tenThou);
     System.out.println(thou);
     System.out.println(hun);
     System.out.println(tens);
     System.out.println(ones);
    

    This gives:

    1000000 (Millions)
    300000  (Hundred thousands)
    50000   (Ten thousands)
    1000    (Thousands)
    200     (Hundreds)
    80      (Tens)
    0       (Ones)
    

    The modulus operator gives you the remainder so 30 % 8 = 6 which is something like (30/8) = 3. And 30-(3*8) = 6;