作为 ruby 挑战的一部分,我正在制作一个自定义方法 num_to_s(num,base) ,它接受一个数字和基数,并返回一个带有新基数的字符串。
这个问题给了我提示,你可以通过这个操作找到每个数字的值——
(123 / 10**0) % 10 == 3 # ones place
(123 / 10**1) % 10 == 2 # tens place
(123 / 10**2) % 10 == 1 # hundreds place
所以,我创建了以下函数——
def num_to_s(num, base) 
    values =  ["0", "1", "2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
    answer_array = []
    highest_power = 0 
    #find the highest power
    while base**highest_power <= num
        highest_power+=1
    end
    current_power = 0 
    #run a loop to find the values for base**0 to the highest power
    while current_power <= highest_power
        digit = values[ ((num / base**current_power) % base) ]
        answer_array << digit
        current_power +=1
    end
    answer_array.reverse.join
end
num_to_s(4,2)
num_to_s(20,16)
当我运行这个函数时,一切都很好,除了有时答案以 0 为前缀。如果我要删除 0,答案将是正确的。
只是出于好奇,为什么方法中会出现0?
例子 -
num_to_s(5,2) #=> 0101
虽然实际答案是 101