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?
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.
List<Integer> digits(int i) {
List<Integer> digits = new ArrayList<Integer>();
while(i > 0) {
digits.add(i % 10);
i /= 10;
}
return digits;
}
Use the mod 10 rule...
List<Integer> digits = new ArrayList<Integer>();
while (n > 0) {
digits.add(n%10);
n/=10;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With