We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Note that in C++ char is generally a signed 8-bit value. Also note that the lower case character 'z' has a value of 122 (decimal). So we can only rotate it by 5 before the rotation will cause it to go past what a signed 8-bit variable can hold as a positive value. Rotate by 6 and you will have hit 128, which wraps around to a negative value. So if you rotate 'z' by 6 and then ask if the result is greater than 'z', the answer will be no!!!!
This was the problem I had. There are various ways to handle it, such as albrio1's computing whether the rotation should be positive or negative, taking into account the question of it flowing past the end of the alphabet. Another is to copy the character into a larger type, e.g. an int, doing your rotations there and then copying back.
Neat. I have used this problem before with students and never noticed the issue of overflowing as I simply had always used rotations of 5 or less, since we could easily figure in our heads what the result would be!
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Caesar Cipher
You are viewing a single comment's thread. Return to all comments →
Note that in C++ char is generally a signed 8-bit value. Also note that the lower case character 'z' has a value of 122 (decimal). So we can only rotate it by 5 before the rotation will cause it to go past what a signed 8-bit variable can hold as a positive value. Rotate by 6 and you will have hit 128, which wraps around to a negative value. So if you rotate 'z' by 6 and then ask if the result is greater than 'z', the answer will be no!!!!
This was the problem I had. There are various ways to handle it, such as albrio1's computing whether the rotation should be positive or negative, taking into account the question of it flowing past the end of the alphabet. Another is to copy the character into a larger type, e.g. an int, doing your rotations there and then copying back.
Neat. I have used this problem before with students and never noticed the issue of overflowing as I simply had always used rotations of 5 or less, since we could easily figure in our heads what the result would be!