我正在构建一个基数转换器。这是我的代码:
def num_to_s(num, base)
results = []
remainders = []
while base <= num
result = num / base #divide the initial value of num
num = result #put that back in num so you can do it again
results << num #push into array, then map for remainders
end
remainders << results.map{|i| result = i % base} #get remainders (doesn't shovel first one?)
first_remainder = num % base #since the first remainder isn't getting recorded
return (first_remainder.to_s + remainders.to_s).reverse
end
num_to_s(13346, 7)
从结果数组中收集余数的模数不会从该数组的第一次迭代中获取余数。我通过给第一个modulo操作补救了跳过它自己的单独变量,这可能是一个便宜的黑客,但它的工作原理。为什么会这样?是否有更好的方法来修复它(没有一些彻底的改造)?
它需要转换为基数16.我知道这不会转换基数16因为涉及的字母,我会想到当我到达它。但我也愿意就此提出建议。
答案 0 :(得分:0)
您执行的第一项操作是按基数模数。这就是为什么不保留初始值。因此,最简单的方法就是最初将它放入数组中:
def num_to_s (num, base)
results = [num] # keep the initial
while base <= num
num /= base # divide the initial value of num
results << num # push into array, then map for remainders
end
# reverse an array and only then join it into string
results.map {|i| i % base}.reverse.join
end
puts num_to_s(13346, 7)
#⇒ 53624