Skip to content

Instantly share code, notes, and snippets.

@ZaneMeroff
Last active April 2, 2020 15:56
Show Gist options
  • Save ZaneMeroff/e167ab3f361b82e39d2d9cd3fbc6eea4 to your computer and use it in GitHub Desktop.
Save ZaneMeroff/e167ab3f361b82e39d2d9cd3fbc6eea4 to your computer and use it in GitHub Desktop.
/*
Write a recursive function that converts an integer into a string such that the number is represented in Roman Numerals in the most efficient way.
eg, the number 4 could be written as 'IIII' but it's more efficient to use 'IV' since that's a shorter string
Assume no number is greater than 4,000
Here are the Roman Numeral equivalents you'll need to know:
M=1000, CM=900, D=500, CD=400,
C=100, XC=90, L=50, XL=40,
X=10, IX=9, V=5, IV=4, I=1
*/
function to_roman(num) {
// your code goes here
}
console.log(to_roman(128)); // should return "CXXVIII"
console.log(to_roman(2000)); // should return "MM"
console.log(to_roman(2017)); // should return "MMXVII"
console.log(to_roman(1999)); // should return "MCMXCIX"

Rewrite the question in your own words:

  • The problem is asking to write a function that will take in a number and will return a string of roman numerals that corresponds with the number coming in. I am to use the roman numeral key provided.

What are your initial thoughts about this problem? (high level design, 2-3 sentences)

  • The problem that is being asked seems simple enough, as far as what it is asking me to do. However, I believe the solution may be more complex. My initial thought is to write a function with a series of conditionals regarding the num coming in and it will convert parts of the num to a string, then add that string to the output of calling the function again. The will need to be a condition for when the num is coming in is empty to stop the process.

Which data structure(s) do you think you'll use? What pros/cons do you see about using it/them?

  • I know my solution will need to be a recursive fucntion, since that is the learning goal for this technical challenge.

Write out your initial pseudocode: (mid-level design, this should not be real code!)

  1. Define the function and set a parameter of num for my input
  2. Write a series of conditionals checking if the number coming in is first >= 1000, if so return M + call the function again and with the num - 1000
  3. Do this for each roman numeral character
  4. Write one last condition that checks if there isn't a num coming in, and if so return the last value.

What do you think the Big O complexity of your algorithm is? (just for practice)

  • Since it appears my solution doesn't involve an iterator method, just conditionals without using state, I believe my Big O complexity is 0(log n) logarithmic time?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment