我有一个任务,我需要写一个编码器与这些要求:
输入:从 1 到 8 位的整数(即 12345678 、 2352 、 76543)
输出:固定大小的 6 位代码,可以包含任何字母数字和符号(a-z,A-Z,0-9,!@ # $% *()|-_= + ^ /?)
操作必须是可逆的,所以给定一个代码,它应该解码回原始整数
输出代码不需要加密安全
我没有使用 crypto(?)或编码算法的经验,所以我不知道如何完成这项工作。我在网上找到的库不允许设置输出大小,因为它基于输入大小。
任何帮助是强烈赞赏,我在这里失去了

当我看到这个时,我很兴奋,所以我做了一个答案,至少做了这个问题所需要的:D
编码通过基本转换逻辑和将这些数字转换为文本来工作。我使用长度为 6 的数组来存储编码上的数据,以确保它始终是 6 个字符(而不是更少)
解码的工作原理是只需将其添加回尊重的权力,所以它添加回全值
我希望这是你正在寻找的答案,因为我喜欢这个问题:D
//a homemade answer :D
//first time I saw a question like that, I hope I get stuff like this in college ngl
function encode(num){
let alphabet=[]
for(let i=48;i<127;i++){
alphabet.push(String.fromCharCode(i))
}
//alphabet is filled with encoding text :D
let arr=[0,0,0,0,0,0] //for fixed 6 digits
let pow=0; let pow1=1
let length=alphabet.length
while(num>0){
let subtraction=(num%Math.pow(length,pow1))
num-=subtraction
arr[pow]=subtraction/Math.pow(length,pow)
pow++; pow1++
}
return arr.reverse()
.map(a=>String.fromCharCode(a+48)) //offset of 48 for nice chars
.join('') //like a base conversion basically
}
function decode(string){
let num=0; let length=127-48 //length really is the number of base(79 in this case)
string=string.split('').reverse().join('')
for(let i=0;i<string.length;i++){
let int=string.charCodeAt(i)-48 //-48 remembering the offset
num+=int*Math.pow(length,i)
}
return num
}
var int=12348291
console.log('encoded num:',encode(int))
console.log('decoded string:',decode(encode(int)))
console.log('they are reversible?',decode(encode(int))==int)

这里有一个简单的方法:
将输入转换为字符串,并根据需要通过向左添加零来扩展到 9 位
使用 base32 编码对每组 3 位数字进行编码,每组最多给您两个字母 / 数字,您可以在测试时使用.toString(32)
,但我想面试官希望您创建自己的函数
将每组填充到长度 2 并连接
例子:
1234567 -> 001234567 -> 001 234 567 -> 1 7a hn -> 017ahn
祝你好运
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(85条)