Caesars Cipher not getting desired output?

Tell us what’s happening:
I’m not getting the desired output.
Instead of getting output as FREE CODE CAMP, this is what I’m getting:
FREE-CODE-C[MP. My code is given below. Help is appreciated.
Your code so far

function rot13(str) { // LBH QVQ VG!
  arr1 = [];
  for(var i=0;i<str.length;i++){
    if(str.charCodeAt(i)>=65 || str.charCodeAt(i)<=90){
      if(str.charCodeAt(i)<=78){
        arr1[i] = String.fromCharCode(str.charCodeAt(i)+13);
      }
      else{
        arr1[i] = String.fromCharCode(str.charCodeAt(i)-13); 
      }
    }else{
        arr1[i] = str.charCodeAt(i);
    }
  }
  return arr1.join("");
}

// Change the inputs below to test
rot13("SERR PBQR PNZC");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/caesars-cipher

Firstly,according to the problem statement you are supposed to decode only the uppercase letters where the character code is between 65 and 90, but your program decodes all the characters whose char code is >= 65 or <=90 which also includes space because the char code for space is 32 and is sure <= 90.

Secondly,add 13 to characters whose char code is <=77 because when you use <=78, N char code is 78,so 78+13=91 which is ‘[’.

Always use console.log() to check where your program goes wrong!

1 Like