The Exercise That Set Me In Motion: Base Conversion

Ruth Hill
Ruth Hill
Mar 1, 2018 · 4 min read

“Write a method that takes two integers - the first representing a decimal number to be converted, and the second representing a numeric base between 2 and 16. The method should convert the decimal number into the new base and then return it as a string.”

def num_to_str(num, base)
if num < base
return num
end
remainders = []
until num < base
remainders << num % base
num /= base
if num < base
remainders << num
end
end
new_number = []
remainders.each do |digit|
new_number.unshift(digit)
end
return new_number.join("")
end
  int_str_hash = Hash.new(0)  (0..9).each do |x|
int_str_hash[x] = x.to_s
end
int_str_hash[10] = "A"
int_str_hash[11] = "B"
int_str_hash[12] = "C"
int_str_hash[13] = "D"
int_str_hash[14] = "E"
int_str_hash[15] = "F"

Ruth Hill

Written by

Ruth Hill

JavaScript developer, maker, proponent of science, compassion & enthusiasm

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade