简体   繁体   English

加密后无法得到正确的字母

[英]Can't get right letter after ciphering

I am working on this problem at CodeWars: Vowels Back Usually half of my tests fail, but from what I see every fail test is because of letter 'a' since I get '\backslash' instead of 'v'.我正在 CodeWars 上解决这个问题:元音返回通常我的一半测试失败,但从我看到的每个失败测试都是因为字母 'a' 因为我得到的是 '\backslash' 而不是 'v'。 Of course, I see from my calculations why I get '\backslash', I tried to fix it with something like Math.abs(), but then I was getting 'f', not 'v'.当然,我从我的计算中看出为什么我得到'\backslash',我试图用类似Math.abs()的东西来修复它,但后来我得到的是'f',而不是'v'。 Can someone help me fix this please?有人可以帮我解决这个问题吗? All other letter changes seem correct.所有其他字母更改似乎都是正确的。

 function vowelBack(s){ let output = ''; let position; let newPosition; let newChar; for (let i = 0; i < s.length; i++) { position = s.charCodeAt(i); if (s[i] === 'c' || s[i] === 'o') { newPosition = ((position - 97 - 1) % 26) + 97; newChar = String.fromCharCode(newPosition); if (newChar === 'c' || newChar === 'o' || newChar === 'd' || newChar === 'e') { newChar = s[i]; } output += newChar; } else if (s[i] === 'd') { newPosition = ((position - 97 - 3) % 26) + 97; newChar = String.fromCharCode(newPosition); if (newChar === 'c' || newChar === 'o' || newChar === 'd' || newChar === 'e') { newChar = s[i]; } output += newChar; } else if (s[i] === 'e') { newPosition = ((position - 97 - 4) % 26) + 97; newChar = String.fromCharCode(newPosition); if (newChar === 'c' || newChar === 'o' || newChar === 'd' || newChar === 'e') { newChar = s[i]; } output += newChar; } else if (s[i] === 'a' || s[i] === 'i' || s[i] === 'u') { newPosition = ((position - 97 - 5) % 26) + 97; newChar = String.fromCharCode(newPosition); if (newChar === 'c' || newChar === 'o' || newChar === 'd' || newChar === 'e') { newChar = s[i]; } output += newChar; } else { newPosition = ((position - 97 + 9) % 26) + 97; newChar = String.fromCharCode(newPosition); if (newChar === 'c' || newChar === 'o' || newChar === 'd' || newChar === 'e') { newChar = s[i]; } output += newChar; } } return output; } console.log(vowelBack("testcase"));

In javascript, -b < (a % b) < b , as opposed to 0 <= (a % b) < b in mathmatical notation (so -1 % 5 == -1 , not 4 ).在 javascript 中, -b < (a % b) < b ,而不是数学符号中0 <= (a % b) < b (所以-1 % 5 == -1 ,而不是4 )。 To ensure a positive solution, write (((a % b) + b) % b) .为确保得到正解,请编写(((a % b) + b) % b)

In your situation, I would add a function:在您的情况下,我会添加一个 function:

function shiftLetter(position, shift) {
    return ((((position - 97 + shift) % 26) + 26) % 26) + 97;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM