int number; (This would be your credit card number)
while (number > 0) {
System.out.println( number % 10);
number = number / 10;
}
This will print them in reverse order. You can perform your operations on the digits this way.
문제
I need to write a Java program that validates credit card numbers, and to do that I need to preform operations on each individual digit. How can I get these digits, without using strings or arrays?
해결책
int number; (This would be your credit card number)
while (number > 0) {
System.out.println( number % 10);
number = number / 10;
}
This will print them in reverse order. You can perform your operations on the digits this way.
다른 팁
Assuming you're using a 64 bit integral type (which is sufficient for a 16 digit card number), a long
will do the trick; e.g. long num
.
use num % 10
to extract the rightmost digit.
use num / 10
to remove the rightmost digit.
That's all you need to do (in a loop structure obviously), but why do it like this anyway? Do a good job instead. Use http://en.wikipedia.org/wiki/Luhn_algorithm with which credit card numbers comply.