how a splitting number to a separate digits algorithm works

i'm getting back to software development and i was playing around with algorithms in java,and today i'm doing the algorithm the splits a number to a separate digits, I've found it here i wrote it in java ..it works but honestly i don't how ?? there is the code just i didn't understand a part of it :

public static void main(String[] args) {
    Integer test = 0, i, N;
    ArrayList array_one= new ArrayList<Integer>();
    Scanner sc = new Scanner(System.in);

    System.out.print("Write An Integer :");
    test = sc.nextInt();
    while (test > 0){
      int mod = test % 10; // <= DON'T UNDERSTAND THE WORK OF THAT PART
                           // (i know it's the modulo of the entered value)
       test = test / 10;
       array_one.add(mod);
    }
    System.out.print(array_one);
}

i know it's a newbie question i'm just passionate about software engineering and algorithms just want to know how it exactly works and thks in advance.

Upvotes: 0

Views: 3294

Answers (5)

apex05
apex05

Reputation: 1

The logic used here is to separate the units place first by dividing the number by 10 and getting the reminder value.

e.g x=153

"% " is the modulus operator that gives the remainder of the division "/" is the division operator that gives only the quotient

then 153%10= 3 //this is the remainder that separates the first digit. The number is then divided by 10 so as to get the quotient

i.e 153/10 =15 // Only the quotient

Progressing with the loop, now 15 is taken as the new original number and is again divided by 10 to get the remainder and hence the next digit.

i.e 15%10 =5 //next digit 15/10=1;

 1%10=1    //digit
 1/10=0   //The loop ends here

Upvotes: 0

M-Garebaghi
M-Garebaghi

Reputation: 89

You can understand it by an example
Your number to divide it's digits is 345
If you divide it by 10 your remaining and first digit is 5

Upvotes: -1

TheLostMind
TheLostMind

Reputation: 36304

test % 10;  --> Always gives you the last digit.
 test / 10; --> divides the existing number by 10.
 while loop --> executes until test > 0

So, if your number is 234,
234%10 would be 4
234/10 would be 23.4 which will be converted to 23.

Apply 23 % 10 and 23/10 and so on..

Upvotes: 1

Michael Laffargue
Michael Laffargue

Reputation: 10294

By using %10 you'll get only the last digit. /10 will give what is before your last digit.

And so you can construct your array.

124%10 --> 4
124/10 --> 12   % 10 --> 2
             12 / 10 --> 1

Upvotes: 0

Eran
Eran

Reputation: 393781

test % 10; gives you the last (least significant) digit of the number, which is the remainder when dividing the number by 10.

test = test / 10 reduces the number by one digit (123456 becomes 12345), making the former 2nd least significant digit the new least significant digit. Therefore, in the next iteration, test % 10; would return the 2nd digit.

And so on...

Upvotes: 1

Related Questions