Hello Amany,
The reason the above code produces incorrect results on certain test cases is due to the lack of wrap-around when a character's ASCII value is shifted by an integer. Here is a simple example for better understanding:
- The digit '0' has an ASCII value of 48. When shifted by 3 positions, it becomes ASCII 51, representing digit '3', which works as expected.
- However, when the digit '8', with an ASCII value of 56, is shifted by 3 positions, it becomes ASCII 59, which does not correspond to the digit '1'. Instead, the ASCII value should wrap-around to 49, representing digit '1'.
The wrap-around can be achieved using the 'mod' function. Refer to this documentation for more information on it:
Here are some example code snippets to wrap-around ASCII values:
if (x(jj) >= 48) && (x(jj) <= 57)
x(jj) = mod(x(jj) - 48 + shift, 10) + 48;
- For lowercase alphabets a to z:
if (x(jj) >= 97) && (x(jj) <= 122)
x(jj) = mod(x(jj) - 97 + shift, 26) + 97;