c++ - 将十进制转换为平衡的 Heptavintimal

标签 c++ base base-conversion ternary-representation

我正在尝试制作一个将十进制转换为平衡的 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 

最佳答案

刚刚开始工作,这是代码:

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++ 模和修改更新值的方式可以达到目的。

关于c++ - 将十进制转换为平衡的 Heptavintimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56169745/

相关文章:

c++ - 使用assert(f<char, int>()) 编译错误

c++ - 如果不从派生构造函数调用基类构造函数会怎样?

c++ - 十进制左移除法

c++ - 使用位运算符将十进制转换为八进制

在 C 中将 Base 16(十六进制)转换为 Base 36 字符串

c++ - 了解文件格式和图像格式的剖析

c++ - 如何从存储在列表中的对象调用成员函数

c++ - || while 条件下的运算符(operator)未按预期工作

r - 如何获得最后一个非零元素的位置

java - 在java中实现抽象方法/类