将自然数转换为tribit字符串的简单算法是什么?

时间:2016-04-18 15:26:14

标签: javascript algorithm data-structures numbers

这是从自然数到基数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
...

来回执行此映射的最简单,最有效的功能是什么?

2 个答案:

答案 0 :(得分:1)

这需要一些技巧,但可以使用Number.prototype.toStringparseInt完成:

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映射到空字符串)

答案 1 :(得分:0)

没关系,事实证明这很明显:

function to(base, nat){
    var digits = [];
    while (nat >= 0){
        digits.push(nat % base);
        nat = Math.floor(nat/base)-1;
    };
    return digits;
};
function from(base, digits){
    var nat = digits[digits.length-1];
    for (var i=digits.length-2; i>0; --i)
        nat = (nat + 1) * base + digits[i];
    return nat;
};
但是,这些三位一体是相反的。我想知道是否有办法在不使用reverse的情况下获得正确的顺序(同时推送到数组的末尾)。