Convert decimal to balanced Heptavintimal

允我心安 提交于 2021-01-27 06:31:37

问题


I'm trying to make a function to convert decimal to balanced Heptavintimal (0123456789ABCDEFGHKMNPRTVXZ) where 0 represent -13, D : 0 and Z 13

I have tried this but some cases are not working properly:

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;
}

Here is what I get in this example -14, -15, 14, 15 isn't working

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 

回答1:


Just got it working, here is the code:

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;
}

Apparently a mix of mathematical modulo, C++ modulo and modifying the way you update your value did the trick.




回答2:


You're using mod (%) incorrectly. It's difficult/complicated to know what a signed int will initially be set to. So try this instead:

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

Of course you'll have to deal with the sign of your conversion separately:

int sign = value >= 0 ? 1 : -1;


来源:https://stackoverflow.com/questions/56169745/convert-decimal-to-balanced-heptavintimal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!