4

我正在尝试创建一个函数来将十进制转换为平衡的 Heptavintimal (0123456789ABCDEFGHKMNPRTVXZ),其中 0 代表 -13,D:0 和 Z 13

我已经尝试过了,但有些情况无法正常工作:

static const std::string HEPT_CHARS = "0123456789ABCDEFGHKMNPRTVXZ";

std::string heptEnc(int value){
    std::string result = "";

    do {
        int pos = value % 27;
        result = std::string(HEPT_CHARS[(pos + 13)%27] + result);
        value = value / 27;
    } while (value != 0);

    return result;
}

这是我在这个例子中得到的 -14、-15、14、15 不起作用

call(x) - expect: result
heptEnc(-9841) - 000: 000
heptEnc(-15) - CX: 
heptEnc(-14) - CZ: 
heptEnc(-13) - 0: 0
heptEnc(-1) - C: C
heptEnc(0) - D: D
heptEnc(1) - E: E
heptEnc(13) - Z: Z
heptEnc(14) - E0: 0
heptEnc(15) - E1: 1
heptEnc(9841) - ZZZ: ZZZ 
4

2 回答 2

3

刚刚开始工作,代码如下:

static const std::string HEPT_CHARS = "0123456789ABCDEFGHKMNPRTVXZ";

inline int modulo(int a, int b) 
{
    const int result = a % b;
    return result >= 0 ? result : result + b;
}

std::string heptEnc(int value)
{
    std::string result = "";

    do {
        int pos = value%27;
        result = std::string(HEPT_CHARS[modulo(pos + 13,27)] + result);
        value = (value+pos) / 27;
    } while (value != 0);

    return result;
}

显然,数学模数、C++ 模数和修改更新值的方式的组合可以解决问题。

于 2019-05-16T15:06:38.627 回答
1

%错误地使用了 mod ( )。知道 asigned int最初将设置为什么是困难/复杂的。所以试试这个:

unsigned int uvalue = std::abs(value);
unsigned int upos = uvalue % 27;
int pos = static_cast<int>(upos) - 13;

当然,您必须单独处理转换的标志:

int sign = value >= 0 ? 1 : -1;
于 2019-05-16T13:44:39.173 回答