In: Computer Science
write C# console app No arrays
Credit card validation Problem. A credit card number must be between 13 and 16 digits. It must start with: –4 for visa cards –5 for mater cards –37 for American express cards –6 for discover cards •Consider a credit card number 4380556218442727 •Step1: double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number. •Step2: now add all the single digit numbers from step1 4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 •Step3: add all digits in the odd places from right to left in the card number 7+ 7 + 4 + 8 + 2 + 5 + 0 + 3 = 36 •Step4: sum the results from step 2 and step 3 37 + 36 = 73 •Step 5: if the results from step 4 is divisible by 10, the card number is valid; otherwise, it is invalid. In this case, the card number is not valid – because 75 not divisible by 10. use modulus operator
using System;
using System.Linq;
using System.Text;
using System.IO;
namespace SO
{
class Program
{
static void Main(string[] args)
{
string[] cards = new string[] {
"378282246310005",
"4012888888881881",
"6011111111111117",
"4222222222222",
"76009244561",
"5019717010103742",
"6331101999990016",
"30569309025904",
"5147004213414803",
"6011491706918120",
"379616680189541",
"4916111026621797",
};
foreach (string card in cards)
{
Console.WriteLine(IsValid(card));
}
Console.ReadLine();
}
public static bool IsValid(object value)
{
if (value == null)
{
return true;
}
string ccValue = value as string;
if (ccValue == null)
{
return false;
}
ccValue = ccValue.Replace("-", "");
ccValue = ccValue.Replace(" ", "");
int checksum = 0;
bool evenDigit = false;
foreach (char digit in ccValue.Reverse())
{
if (digit < '0' || digit > '9')
{
return false;
}
int digitValue = (digit - '0') * (evenDigit ? 2 : 1);
evenDigit = !evenDigit;
while (digitValue > 0)
{
checksum += digitValue % 10;
digitValue /= 10;
}
}
return (checksum % 10) == 0;
}
}
}