Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting each digit in an int [duplicate]

Tags:

java

So I'm in a process of writing a small encrypter program. I start by asking the user to enter a 4 digit number (>= 1000 and <= 9999). I'd like to extract each digit from the number entered by the user, and store them in a variable.

My assignment gives me hint which doesn't help me much (Hint: integer division and the modulus might be useful here).

like image 319
JKawa Avatar asked Feb 06 '23 23:02

JKawa


1 Answers

The "hint" is actually a nearly direct explanation of how to do what you need to do: dividing in integers by ten gets rid of the last digit, while obtaining modulo ten gives you the last digit:

int x = 12345;
int lastDigit = x % 10;       // This is 5
int remainingNumber = x / 10; // This is 1234

Do this in a loop until the remaining number is zero. This gives you digits of the number in reverse.

like image 129
Sergey Kalinichenko Avatar answered Feb 08 '23 12:02

Sergey Kalinichenko