题解 | #字符串加解密#
字符串加解密
http://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
#include <stdio.h>
#define DIFF_VALUE ('a'-'A')
static int encrypt_print(char *encrypt, int n)
{
if(!encrypt)
{
return -1;
}
for(int i = 0; i < n; i++)
{
if(encrypt[i] >= 'A' && encrypt[i] <= 'Z')
{
if(encrypt[i] == 'Z')
{
encrypt[i] = 'a';
}
else
{
encrypt[i] += (1 + DIFF_VALUE);
}
}
else if(encrypt[i] >= 'a' && encrypt[i] <= 'z')
{
if(encrypt[i] == 'z')
{
encrypt[i] = 'A';
}
else
{
encrypt[i] += (1 - DIFF_VALUE);
}
}
else if(encrypt[i] >= '0' && encrypt[i] <= '9')
{
if(encrypt[i] == '9')
{
encrypt[i] = '0';
}
else
{
encrypt[i]++;
}
}
}
printf("%s\n", encrypt);
return 0;
}
static int decode_print(char *decode, int n)
{
if(!decode)
{
return -1;
}
for(int i = 0; i < n; i++)
{
if(decode[i] >= 'A' && decode[i] <= 'Z')
{
if(decode[i] == 'A')
{
decode[i] = 'z';
}
else
{
decode[i] += (-1 + DIFF_VALUE);
}
}
else if(decode[i] >= 'a' && decode[i] <= 'z')
{
if(decode[i] == 'a')
{
decode[i] = 'Z';
}
else
{
decode[i] -= (1 + DIFF_VALUE);
}
}
else if(decode[i] >= '0' && decode[i] <= '9')
{
if(decode[i] == '0')
{
decode[i] = '9';
}
else
{
decode[i]--;
}
}
}
printf("%s\n", decode);
return 0;
}
int main()
{
char encrypt[1000] = {0};
char decode[1000] = {0};
gets(encrypt);
gets(decode);
int len1 = strlen(encrypt);
int len2 = strlen(decode);
encrypt_print(encrypt, len1);
decode_print(decode, len2);
return 0;
}