简体   繁体   中英

Caesar Cipher in JavaScript with a Negative Key

I am trying to implement a Caesar Cipher but am unable to get it to work with negative numbers. The function works as expected with a positive key and modulo arithmetic.

var encrypt = function(str, key) {
    const arr = str.split('');
    const newArr = [];
    for (let i=0; i<arr.length; i++) {
        let x = str.charCodeAt(i);
        // Check for lower case letters
        if (x >= 97 && x <= 122) {
            newArr.push((x - 97 + key) % 26 + 97);
        // Check for upper case letters
        } else if (x >= 65 && x <= 90) {
            newArr.push((x - 65 + key) % 26 + 65);
        } else newArr.push(x);
    };
    console.log(newArr);

    // Convert back to characters ...
    const strArr = [];
    for (let i=0; i<newArr.length; i++) {
        strArr.push(String.fromCharCode(newArr[i]));
    };
    return strArr.join('');
        
};

console.log(encrypt('Hello World!', -27));

You need to account for the negative remainder that is returned when the adjusted value falls below your minimum and wrap it back around to the max.

You can achieve this by adding the length of the series (26 in this case) back to the first remainder, getting the new remainder from this adjusted value, and then moving it back to the range that you need.

((x - 97 + key) % 26 + 26) % 26 + 97

 var encrypt = function (str, key) { const arr = str.split(''); const newArr = []; for (let i = 0; i < arr.length; i++) { let x = str.charCodeAt(i); // Check for lower case letters if (x >= 97 && x <= 122) { newArr.push(((x - 97 + key) % 26 + 26) % 26 + 97); // Check for upper case letters } else if (x >= 65 && x <= 90) { newArr.push(((x - 65 + key) % 26 + 26) % 26 + 65); } else newArr.push(x); }; console.log(newArr); // Convert back to characters... const strArr = []; for (let i = 0; i < newArr.length; i++) { strArr.push(String.fromCharCode(newArr[i])); }; return strArr.join(''); }; console.log(encrypt('abcd', -2)); console.log(encrypt('AbCd', -2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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