gpt4 book ai didi

javascript - 将自然数转换为三位字符串的简单算法是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:00:23 26 4
gpt4 key购买 nike

这是一个从自然数到 base-3 字符串的映射:

 0 =>    0
1 => 1
2 => 2
3 => 00
4 => 01
5 => 02
6 => 10
7 => 11
8 => 12
9 => 20
10 => 21
11 => 22
12 => 000
13 => 001
14 => 002
15 => 010
16 => 011
17 => 012
18 => 020
19 => 021
20 => 022
21 => 100
22 => 101
23 => 102
24 => 110
25 => 111
26 => 112
27 => 120
28 => 121
29 => 122
30 => 200
31 => 201
32 => 202
33 => 210
34 => 211
35 => 212
36 => 220
37 => 221
38 => 222
39 => 0000
40 => 0001
...

来回执行此映射的最简单和最有效的函数是什么?

最佳答案

这需要一些技巧,但可以使用 Number.prototype.toString 来完成和 parseInt :

function numToBase3(n) {
var pref = "",
offset = 0,
pow = 3;
while (n >= offset+pow) {
offset += pow;
pow *= 3;
pref += "0";
}
return (pref + (n-offset).toString(3)).slice(-1-pref.length);
}
function base3ToNum(s) {
var offset = 0,
pow = 3;
for (var i=1; i<s.length; i++) {
offset += pow;
pow *= 3;
}
return parseInt(s, 3)+offset;
}

(以 pow = 1i = 0 开始,将 0 映射到空字符串)

关于javascript - 将自然数转换为三位字符串的简单算法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36698271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com