JavaScript算法练习:移位密码|凯撒密码Caesar cipher

2018-03-0906:13:15WEB前端开发Comments5,014 views字数 911阅读模式

位移密码
著名的凯撒密码Caesar cipher,又叫移位密码。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/1366.html

移位密码也就是密码中的字母会按照指定的数量来做移位。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/1366.html

一个常见的案例就是ROT13密码,字母会移位13个位置。由’A’ ↔ ‘N’, ‘B’ ↔’O’,以此类推。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/1366.html

写一个ROT13函数,实现输入加密字符串,输出解密字符串。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/1366.html

所有的字母都是大写,不要转化任何非字母形式的字符(例如:空格,标点符号) // 遇到这些特殊字符,就跳过它们。
Answer:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/1366.html

function rot13(str) {

    var strup = str.toUpperCase(); //把所有字母都转成大写
    var charcodearr = [];
    var rotcodearr = [];
    for (var i = 0; i < strup.length; i++) { //获取strup每个字母的code并push进数组charcodearr里
        var strcode = (strup.charCodeAt(i));
        charcodearr.push(strcode);
    }
    for (var j = 0; j < charcodearr.length; j++) { //凯撒加密,加密后的值push进数组rotcodearr里
        if (charcodearr[j] < 65) {
            rotcodearr.push(charcodearr[j]);
        } else if (charcodearr[j] < 78) {
            rotcodearr.push(charcodearr[j] + 13);
        } else if (charcodearr[j] < 91) {
            rotcodearr.push(charcodearr[j] - 13);
        } else if (charcodearr[j] > 91) {
            rotcodearr.push(charcodearr[j]);
        }
    }

    return String.fromCharCode.apply(this, rotcodearr);
    //成string并返回成字母
}
rot13("SERR PBQR PNZC");

26个字母的unicode码在65(A)与90(Z)之间,第13位M(77);
后13位字母减去13后放入;
前13位字母加上13后放入;
通过.fromCharCode()转化为字母,将数组转化为字符串;文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/1366.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/1366.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定