Today, let's learn how to deal with the mixed operation of characters and numbers.
Speak with questions:
Question A: String decryption
Title Description
Now let a, a stand for the number 0, B, B stand for the number 1, C, C stand for the number 2 Z. Z stands for the number 25.
Enter K, B and string. Please decrypt the letters in the string one b y one according to the rule of y = (k x + b), where x is the number represented by letters. If y exceeds 25, then y will be left over 26.
input
There are multiple groups of test data, each group input two lines:
First line: enter k b (meaning above) (k > 0, b > = 0)
Second line: enter the string to be decrypted (no longer than 5000)
output
One line for each group of test output
First line: decrypted string
sample input
1 4
E hkra OVQ!
2 46
YQY (:з」∠)...
sample output
I love SZU!
QAQ (:з」∠)...
The algorithm of solving this problem is not difficult, as long as a function is written so that every character input will be converted to output according to the corresponding rules, the key point is the preparation of the conversion function.
#include<stdio.h>
#include<string.h>
char zhuanhuan(char a,int k,int b);
int main()
{
int k,b;
char arr[500]={'\0'};
while(scanf("%d%d",&k,&b)!=EOF)
{
getchar();
gets(arr);
/*For EOF with multiple sets of data, you need to input numbers and characters, and also eat spaces
It is recommended to use such branch input to set EOF in the first line instead of thinking about
How to input one time in while condition*/
for(int i=0;i<strlen(arr);i++)
{
printf("%c",zhuanhuan(arr[i],k,b));
}
printf("\n");
}
return 0;
}
char zhuanhuan(char a,int k,int b)
{
if(a>='a'&&a<='z')
{
/*Here's the point today*/
/*In fact, character data can be interpreted as ASCII + '\ 0' (NULL)
NULL It's the first in ASCII*/
a-='a';
/*What's left after subtracting a character from a character is an integer. You can add, subtract and take the rest happily*/
a=(k*a+b);
if(a>25)
{
a=a%26;
}
a=a+'a';
return a;
}
else if(a>='A'&&a<='Z')
{
a-='A';
a=(k*a+b);
if(a>25)
{
a=a%26;
}
a=a+'A';
return a;
}
else
{
return a;
}
}
Hahaha, if you simply copy and paste my code, you will find that you are only 50% wrong later
if(a>='a'&&a<='z')
{
/*a char memory only takes one byte, (int) a max 128*/
a-='a';
a=(k*a+b);
/*But when you do k*a+b, it's easy to overflow. At this time, some data can't be expressed normally
We'd better define an integer c according to the following code, let c express the number after subtracting "a" to solve this problem */
if(a>25)
{
a=a%26;
}
a=a+'a';
return a;
}
if(a>='a'&&a<='z')
{
int c;
c=a-'a';
c=(k*c+b);
if(c>25)
{
c=c%26;
}
a=c+'a';
return a;
}