The original question of a famous software company is as follows: implement the following two functions: char toupper (char c); char tolower (char c ); convert the input letters to uppercase and lowercase letters respectively. The value range of the parameters passed in by the two functions is [a-zA-Z] and is ASCII encoded. The parameter validity does not need to be checked during implementation. The implementation of the two functions cannot use any form of statements or commands such as branch and jump (Note: C/C ++ conditional operators? : It is also a form of branch commands, so it cannot be used ). Write as many methods as possible.
Analysis and Solution: This question is special and has strict restrictions. Based on the requirements of the question, if else, for, while, do while, switch case, and ,? : In addition, only the =, + =,-=, &, |, ^, ++, and -- statements that can be used can be converted to uppercase or lowercase, we can only choose from these statements. Because the character set is ASCII and the range is clearly [a-zA-Z], we know that, a-z corresponds to the ASCII value 97-122, the A-Z corresponds to the ASCII 65-90, observe these numbers, we can find that 97-122 are greater than 96,-90 are greater than 64 and less than 96, further, we can find that the binary format of all lowercase letters is 011 XXXXX, And the binary format of uppercase letters is 010 XXXXX. Once we get there, haha, the answer will come out, it can be achieved through bitwise Operations & and |. The code is described as follows:
1 char toupper (char c)
2 {
3 return c & 0x5F;
4}
5
6 char tolower (char c)
7 {
8 // c | 0x60, but not very good, because 0x60 will change the result's 7th-bit value. According to the meaning of the question, change the 6th-bit value to 1, the other BITs remain unchanged.
9 return c | 0x20;
10}
As for other methods, I don't have to think much about it. I hope you can share more with me.