Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split int value into separate digits

Tags:

java

I want to split my int value into digits. eg if the no. is 542, the result should be 5,4,2.

I have 2 options. 1) Convert int into String & then by using getCharArray(), i can have separate characters & then i will convert them back into int values.

2) Convert int into String, without converting it into char array, iterate it & get all digits.

Is there any other way to solve the problem. If not, which of the option will be fast?

like image 737
Raman Avatar asked Mar 04 '11 16:03

Raman


People also ask

How do you convert a number into a digit?

Step 1 − Divide the decimal number to be converted by the value of the new base. Step 2 − Get the remainder from Step 1 as the rightmost digit (least significant digit) of new base number. Step 3 − Divide the quotient of the previous divide by the new base.


2 Answers

List<Integer> digits(int i) {
    List<Integer> digits = new ArrayList<Integer>();
    while(i > 0) {
        digits.add(i % 10);
        i /= 10;
    }
    return digits;
}
like image 55
corsiKa Avatar answered Oct 03 '22 12:10

corsiKa


Use the mod 10 rule...

 List<Integer> digits = new ArrayList<Integer>();
 while (n > 0) {
     digits.add(n%10);
     n/=10;
 }
like image 43
Andrew White Avatar answered Oct 03 '22 11:10

Andrew White