0
How to extract digits in java.
if there is a 5 digit number how to extract each digit.
6 Answers
+ 5
int number = 12345;
for(int i = 0; i<5; i++){
System.out.println(number%10);
number /= 10;
}
output:
5
4
3
2
1
demo: https://code.sololearn.com/cMtAc900HAHw
+ 3
@Kirk Schafe, ok. This code will work for number with any count of digits:
int number = 12345;
String s = "" + number;
for(int i = 0; i<s.length(); i++){
int t = Integer.parseInt(s.charAt(i) + "");
System.out.println(t);
}
output:
1
2
3
4
5
demo: https://code.sololearn.com/cMtAc900HAHw
+ 1
8 ways to convert an integer to a string
http://javadevnotes.com/java-integer-to-string-examples#p1
Then I might iterate using subString().
Perhaps someone has a better way.
+ 1
@Vladimir Honcharenko
That's interesting. You can even modify it for arbitrary length numbers by breaking when number <10.
+ 1
@V.H. Hey, nice contrast of simple vs. less simple.
0
ya