输入字符串将始终为大写。无需移动任何非字母字符。
例:
function encrypt(str, index) {
var encryptedstr = '';
var code = 0;
for(var i = 0; i < str.length; i++) {
var k = str[i].charCodeAt();
if (k >= 65 && k <= 90) {
code = k + index;
encryptedstr += String.fromCharCode(code);
} else {
encryptedstr += str[i];
}
}
return encryptedstr;
}
console.log( encrypt('ABC', 4) );
但是我的代码正在统计以下实例
1.返回类型应为字符串。
2.加密("ABC", 4( 应等于"EFG">
3.加密("AB C", 2( 应等于 "CD E">
4.encrypt("ABC DEF", 2( 应等于 "CDE FGH">
================================================================================================================================================================================================================================但是我有以下错误
答案应该对任何给定的输入有效。
任何建议??
好的,。
为了应对任何情况,您将需要应对边界,例如。 当我们Z
时,移位 1 应该将我们带回乞讨,例如。 A
所以要做到这一点,我们可以使用模运算符%
,这基本上是除法的余数。
例如。 10 % 3 = 1
,这是因为 10/3 = 31/3,所以余数为 1。
因此,我们所要做的就是将字符移回 0,加上我们的移位,然后将其模数为 26,因为字母表中有 26 个字母。 然后再加65,所以我们的角色又从A
开始了。
最终公式.. -> code = ((k + index - 65) % 26) + 65;
大写和小写 ASCII 执行此操作的方法。
但本质上对于任何字符,获取字符代码查找它的基础(大写 ASCII 为 65,等于 A
(添加您要旋转的字符数,mod 26,例如 X
-> 88 - 65 = 23 -> +4 = 27 -> 27 mod 26 = 1 -> 1 + 65 = 66 -> B
const ceaser = (text, positions) => {
return text.split('').map(ch => {
let charCode = ch.charCodeAt(0)
let base = 0;
// ASCII A-Z
if (charCode >= 65 && charCode <= 90)
base = 65;
// ASCII a-z
if (charCode >= 97 && charCode <= 122)
base = 97;
if (base === 0) return ch;
return String.fromCharCode((((charCode - base) + positions) % 26) + base);
}).join('');
};
console.log(ceaser("Testing 123", 4));
console.log(ceaser("XYZ", 4));
您必须分别处理字母的第一部分,字母和非字母字符的最后一部分
这是代码
function encrypt(str, index) {
var encryptedstr = ''
var newAsciiNum = 0;
for(var i=0;i<str.length;i++){
asciiNum = str[i].charCodeAt();
if( asciiNum>=65 && asciiNum < 91-index){
newAsciiNum = asciiNum + index;//this is where the first past of alphabet letters are been handled
}
else if(asciiNum > 90-index && asciiNum < 90){
newAsciiNum = asciiNum - 26 + index;//this is where last letters of alphabet are been handed
}
else{
newAsciiNum = asciiNum; // this where the no-alpha characters are been handled
}
encryptedstr += String.fromCharCode(newAsciiNum);
}
return encryptedstr;
}
encrypt('ABC', 4);