1
#include <stdio.h>


int main(int argc, string argv[])
{
   Get input from the user;
   Store it in a long long int;

   // iterate through the number
   for each odd number in the input multiply by 2
   if the number is bigger than 9 then
   do module of it and add it to the first number;
   store it into metasum;

   for each even number in the input
   add it to the others;
   store the result into metasum2;

   // is it a valid card?
   if (metasum + metasum2)%10 == 0
   {
   card is valid;
   // check which kind of cc is
   if the input begins with a 3 then it's an AMEX;
   else if the input begins with 4 it is a VISA;
   else if the input begins with 5 it is a MASTERCARD;
   }
   else
   {
   card is not valid;
   }

}

它实际上是一种伪代码。我正在参加 CS50x,我想知道我的伪代码实现是否足够好。

不过我还有另一个问题,当我尝试在 CI 中实现代码时,不知道如何遍历 long long int,所以我无法实现 Luhn 算法。

如何在不使用字符串然后将每个 char 转换为 int 的情况下做到这一点?

感谢您的答复

4

2 回答 2

2

要“迭代”非数组,您需要单独跟踪您的位置(以计算所有可能的数字),使用除法和模数来推进和提取数字,例如:

long long number = 9999999999;
for (int digitPos = 0; digitPos < 16; digitPos++) {
  int thisDigit = number % 10;
  number = number / 10; 
}

至于对你的课程的适用性,我不能保证:)

于 2012-12-05T16:56:22.230 回答
1

使用模数和整数除法。

一个数字的右起第一个数字(最小的数字)是number % 10
第二个是(number/10) % 10。第三个是(number/100) % 10。简单的模式——你可以把它写成一个函数。(只是避免在这里混合浮动。)

如果您想遍历一个数字的位数,您可能需要检查一个数字有多少位(请参阅:以 10 为底的对数) - 最简单的方法是重复将该数字除以 10 直到它为 0。


无论如何,请记住信用卡号码很长!一个无符号的 64 位数字可以包含 19 个有效数字(最大为 2**64-1),因此对于信用卡来说就足够了,但对于银行账户来说就不行了。使用字符串(某种形式)的方法将更通用。

于 2012-12-05T16:59:14.923 回答