|
-
Oct 17th, 2004, 09:55 PM
#1
Thread Starter
Stuck in the 80s
[Resolved] Splitting an Integer into parts?
Let's say I have an integer, greater than 10...can be anything valid for int (10, 100, 1000, etc).
I need to split that number and get the last digit (0 in all the examples above)...so:
Code:
int x = 42;
int y = 422;
for x, I need to separate it into 4 and 2, and for y 42 and 2. I want to do this without casting to a string, if possible.
What I have to do is right a program that does multiplication "by hand", so I need to take the last digit, and carry the rest over.
Hope I explained it well enough to follow. Thanks in advance.
Last edited by The Hobo; Oct 20th, 2004 at 02:43 PM.
-
Oct 18th, 2004, 09:47 AM
#2
Addicted Member
This is what I came up with, seems to work 
PHP Code:
import java.util.Vector;
public class DivideTest
{
public static void main(String arg[])
{
Vector digits = new Vector();
// Some variables
int number = 1234567;
int digit = 0;
int divider = 10;
int sum = 0;
while(true){
digit = number%divider;
digit-= sum;
sum+=digit;
if(digit > 10) digit=digit/(divider/10);
digits.addElement(new Integer(digit));
divider=divider*10;
if(divider>number) break;
}
// Process the last digit
digit=number-sum;
digit=digit/(divider/10);
digits.addElement(new Integer(digit));
Integer curInt;
// Show the digits in the console
for(int i=0;i<digits.size();i++){
curInt = (Integer) (digits.elementAt(i));
System.out.println("Item " + i + ":" + curInt.intValue());
}
}
}
-
Oct 18th, 2004, 10:49 AM
#3
Thread Starter
Stuck in the 80s
I figured this out. Say the number is 54.
Code:
54 % 10 = 4;
54 / 10 = 5;
Seems to work beautifully.
-
Oct 18th, 2004, 01:23 PM
#4
Addicted Member
Yeah, that's what my code does aswell, but it does it for any number of digits
-
Oct 18th, 2004, 09:18 PM
#5
Thread Starter
Stuck in the 80s
Originally posted by Shell
Yeah, that's what my code does aswell, but it does it for any number of digits
My method works for any number of digits as well:
Code:
class test {
public static void main(String[] args) {
System.out.println(144 % 10);
System.out.println(144 / 10);
System.out.println(142343 % 10);
System.out.println(142343 / 10);
}
}
-
Oct 19th, 2004, 03:39 AM
#6
Addicted Member
Oh, didn't read the entire post I gues, I thought you wanted all digits separatly, sorry about that
-
Oct 19th, 2004, 12:17 PM
#7
Thread Starter
Stuck in the 80s
Originally posted by Shell
Oh, didn't read the entire post I gues, I thought you wanted all digits separatly, sorry about that
Oh no. Sorry if I wasn't clear on it. If I ever need code to do that, though, I know where to look. Thanks.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|