将十进制转换为平衡的七进制 [英] Convert decimal to balanced Heptavintimal
本文介绍了将十进制转换为平衡的七进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将十进制转换为平衡的七进制(0123456789ABCDEFGHKMNPRTVXZ)的函数其中0代表-13,D:0和Z 13
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;
}
这是我在此示例中得到的结果-14,-15、14、15无法正常工作
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
推荐答案
就可以了,下面是代码:
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;
}
显然,数学模,C ++模和修改您的值更新方式的结合才是成功的秘诀.
Apparently a mix of mathematical modulo, C++ modulo and modifying the way you update your value did the trick.
这篇关于将十进制转换为平衡的七进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文