Question:
How do you extract digits from an integer in java?
Ronald G.
2009-02-20 14:50:53 UTC
Ok, say I wanted to take a five digit number like "12345," and I wanted to make a java program that took the ones digit, took it out of the integer, and made it its own little digit. How the heck to I do that?

I can (kind of, maybe, not really) get it to add, multiply, or divide... but slicing digits off completely is beyond me.
Four answers:
PhonicUK
2009-02-20 15:00:25 UTC
You use the modulous, divide and floor functions for this.



12345 mod 10 = 5

12345 mod 100 = 45 / 10 = 4.5 (floors to 4)

12345 mod 1000 = 345 / 100 = 3.45 (floors to 3)

12345 mod 10000 = 2345 / 1000 = 2.345 (floors to 2)

12345 mod 100000 = 12345 / 10000 = 1.2345 (floors to 1)



Modulous tells you what would be the remainder after doing a interger-only division.
anonymous
2009-02-20 14:57:16 UTC
Do a modulous (%) operation.



So 12345 % 10 = 5



Then you can divide by ten and repeat to get the tens digit:

12345/10=1234

1234%10=4



So on and so forth.





Another method would be to change the integer to a String and then use the "charAt(x)" method and then parse the character back into an integer, but that's a far worse method.
mohsin
2016-11-15 05:20:04 UTC
write a C language program to seperate digits from a five-digit integer entered by user and print them 3 spaces apart each

reply fast kindly
behney
2016-11-07 06:07:36 UTC
You do precisely an analogous factor. it incredibly is to assert, case in point: int final_digit = (Num<0 ? 0-Num : Num)%10; fixing the final case effectively is slightly extra complicated. A undemanding mindset may well be something like this: public static int digit(int n,int base,int pos) { n = (n<0 ? 0-n : n); base = (base<0 ? 0-base : base); pos = (pos<0 ? 0-pos : pos); whilst(pos>0) { n/=base; pos--; } return (npercentbase); } decrease than some circumstances, you will desire to to alter this to advance overall performance.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...