对于给定的字符串,如"ABC",如果每个字符左移N=1位,则为"ZAB",在TopCoder上作的,时间不长,感觉自己的方法已经很简练了,但是只有160分(满250),郁闷~给个更好的解法~
Problem Statement | |
Julius Caesar used a system of cryptography, now known as Caesar Cipher, which shifted each letter 2 places further through the alphabet (e.g. 'A' shifts to 'C', 'R' shifts to 'T', etc.). At the end of the alphabet we wrap around, that is 'Y' shifts to 'A'. We can, of course, try shifting by any number. Given an encoded text and a number of places to shift, decode it. For example, "TOPCODER" shifted by 2 places will be encoded as "VQREQFGT". In other words, if given (quotes for clarity) "VQREQFGT" and 2 as input, you will return "TOPCODER". See example 0 below. |
代码:
#include <string>
using namespace std;
class CCipher
{public:
string decode(string cipherText, int shift)
{
string ret = "";
int len = cipherText.size();
for(int i=0; i<len; i++)
{
char tmp='Z'-cipherText[i]+shift;
tmp=tmp%26;//移位后于Z的距离~
ret+=('Z'-tmp);//计算出对应的字符
}
return ret;
}
};
同样可以计算出右移,只需要将char tmp=cipherText[i]-'A'+shift ret+=('A'+tmp)就可以了~
看了一个别人的代码:
ret+=cipherText[i]-shift<'A'?(cipherText[i]+'Z'-'A'+1-shift):(cipherText[i]-shift)确实简单~