将给定的字符串里面的每个字符左移N位(TopCoder)

对于给定的字符串,如"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)确实简单~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值