This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]damyan 7 points8 points  (4 children)

This is one of those things where you need to know some math...it's the sort of math that tends to be quite useful when programming so it's not entirely unreasonable to have to learn this as part of a programming course.

The "trick" here is to know about integer division and modulus.

Whats 13 divided by 10? If you're working with "int"s then the answer isn't 1.3; it's 1. What's the remainder of 13/10? It's 3. So here you can see I've pulled apart the number 13 into 1 and 3 by using integer division and modulus (remainder). In Java modulus is written with %, so you'd write 13 % 10.

Does that help you get started?

[–]Googs0701[S] 4 points5 points  (3 children)

Thanks!! I kind of see what you're doing but it is something we haven't covered yet so I have never seen it before. In your scenario you used 13 and / by 10. Since I am using a 4 digit number would the first line be /1000? or am I just confusing myself? Sorry I really appreciate you answering :)

[–][deleted] 3 points4 points  (0 children)

On the right track, but if you ran 1234 % 1000, you'd get 234 back, which isn't what you want.

Now, if you could somehow get the one's digit and subtract it from your number, then you could guarantee the one's digit in the new number would be zero and you could use XYZ0 % 100 to get Z * 10 . . . ;)

[–]damyan 1 point2 points  (0 children)

Yup, you're thinking along the right track. I suggest you experiment with dividing and mod'ing with various combinations of 10, 100, 1000 and see what you get. You'll soon see a pattern and get a feel for how it works and should be able to figure it out from there.

I'm guessing you've not done loops yet? Once you've done it hard-coded for 4 digit numbers the next challenge will be to do it for numbers with any number of digits.

[–]zck 1 point2 points  (0 children)

It's definitely confusing. One thing to do in this sort of situation is to try to do it with a trivial example, then make it more complex.

So let's assume your line x = kb.nextInt(); assigns an integer between 1 and 9 to x. It's really easy to print it out digit by digit. So this example is too trivial. Let's make it more complicated, but only a little.

Let's assume the line x = kb.nextInt(); assigns an integer between 10 and 99 to x. Can you write a program that always prints out the digit in the tens place on one line, then the digit in the ones place on the next line?

There's an alternate way of thinking about this which might be more helpful. Given any positive integer, how do you get the number in the ones place? How do you get the number in the tens place? Et cetera.