C 从十进制到三进制的快速基数转换
有没有什么方法可以将十进制数更改为三进制数? 我的意思是我不想使用模和除法,我有很大的十进制数,例如 128123832812381835828638486384863486........................1237127317237 等等。
也不想使用bigint。
有什么方法吗?
is there any method of changing decimal number to ternary ?
I mean i don't want to use modulo and divide method, i have very big decimal number, something like 128123832812381835828638486384863486.............1237127317237 and so on.
Also don't want to use bigints.
Is there any method ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不必使用除法/模数。相反,从低到高迭代输入数字。对于每个数字位置,首先计算输出表示中的
1000....000
(它是之前的 10 次幂的 10 倍)。然后将该结果乘以数字,并累加到输出表示形式中。您将需要在输出表示中执行乘法和加法的例程。乘法例程可以用加法例程来编写。
示例:
将 246(基数 10)转换为基数 3。
首先初始化输出“累加器”
a = “0”
。初始化“乘数”
m = “1”
。另请注意,10 在输出表示中是
"101"
。第一个数字是 6,即
d = "20"
。t = d * m = "20" * "1" = "20"
。a = a + t = "0" + "20" = "20"
。m = m * "101" = "1" * "101" = "101"
。第二个数字是 4,即
d = "11"
。t = d * m = "11" * "101" = "1111"
。a = a + t = "20" + "1111" = "1201"
。m = m * "101" = "101" * "101" = "10201"
。第三位数字是 2,即
d = "2"
。t = d * m = "2" * "10201" = "21102"
。a = a + t = "1201" + "21102" = "100010"
。所以答案是
“100010”
。You don't have to use divide/modulo. Instead, iterate over the input digits, from low to high. For each digit position, first calculate what
1000....000
would be in the output representation (it's 10x the previous power of 10). Then multiply that result by the digit, and accumulate into the output representation.You will need routines that perform multiplication and addition in the output representation. The multiplication routine can be written in terms of the addition routine.
Example:
Convert 246 (base-10) to base-3.
Start by initialising output "accumulator"
a = "0"
.Initialise "multiplier"
m = "1"
.Note also that 10 is
"101"
in the output representation.First digit is 6, which is
d = "20"
.t = d * m = "20" * "1" = "20"
.a = a + t = "0" + "20" = "20"
.m = m * "101" = "1" * "101" = "101"
.Second digit is 4, which is
d = "11"
.t = d * m = "11" * "101" = "1111"
.a = a + t = "20" + "1111" = "1201"
.m = m * "101" = "101" * "101" = "10201"
.Third digit is 2, which is
d = "2"
.t = d * m = "2" * "10201" = "21102"
.a = a + t = "1201" + "21102" = "100010"
.So the answer is
"100010"
.