Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting digits of int in Java

So if I have an inputted integer:

int num_1 = 128

How would I be able to parse through the number and obtain a 1, 2 and 8, and assign them to different variables?

Thanks!

like image 933
Sean Avatar asked Sep 28 '13 03:09

Sean


1 Answers

I think you can use this solution :

int getDigit(int num,int location){
    return BigDecimal.valueOf(num/Math.pow(10,position)).intValue() %10;
  }

in this solution what will happen is the following you are sending a number due to usage of Math that returns a double we need to convet it again to integer we use the BigDecimal. the main idea or logic is the Math.pow with the position it returns the prefix of number and then the module chops the other end. you can check it with the following Sample:

    System.out.println(getDigit(123456,1));
    System.out.println(getDigit(123456,2));
    System.out.println(getDigit(123456,3));
    System.out.println(getDigit(123456,4));
    System.out.println(getDigit(123456,5));
    System.out.println(getDigit(123456,10) );  

Enjoy

like image 112
Shay Dratler Avatar answered Sep 18 '22 05:09

Shay Dratler