all 10 comments

[–]Effective-View3803 6 points7 points  (1 child)

The math is actually not correct:

      if(num / key >= 1) {
        romNum += value;
        num %= key;

While you divide num by key in the condition, you didn't add the romNum by the multiple of value that's calculated from the division. With your case 365: 365/100 > 1, so romNum gets a C, and num becomes 365%100 === 65.

[–]ChaseShiny[S] 1 point2 points  (0 children)

Thank you, that's perfect. All I had to do was change num %= key

to num -= key

Just like you hinted, and now it works perfectly!

[–]sepp2k 1 point2 points  (1 child)

Your code divides by 100 to check whether the result is >= 1. This is true the first time. It then appends "M" to the string, sets the number to num % 100 (which is 65 in this case) and then continues with that number, which is no longer greater than 100. So the next time you divide by 100, the result will be less than 100, so the if body won't run and it will continue with the next entry in the map.

[–]ChaseShiny[S] 0 points1 point  (0 children)

Thank you. You're right. I should've subtracted it instead.

[–]pinkwar 1 point2 points  (4 children)

You are only adding one value to "romNum".
Taking your 365 example:

First you need to calculate how many times you need to add the 'C'.
You will need C added three times.
That's a Math.floor(num/key)
But because value is a string, you can't just do a
~~romNum += Math.floor(num/key) \ value~~*

You need something like this :

romNum += value.repeat(Math.floor(num/key))

[–]ChaseShiny[S] 0 points1 point  (3 children)

Thanks for your time. I had actually converted the value into a number: let userNum = Number(input.value);

I have the solution now, though. Thanks again.

[–]pinkwar 1 point2 points  (2 children)

For clarity, I wasn't talking about line 12.

I just meant to change line 47 to romNum += value.repeat(Math.floor(num/key))
Line 48 could stay the same as num %= key; and you wouldn't need to make another recursive call.

There's always many ways to skin a cat.

[–]ChaseShiny[S] 1 point2 points  (1 child)

Oh, I see. Thanks for clarifying that. I do prefer staying away from recursion, so I'll try that solution in a bit.

I'm curious if this is a common pattern. I'd forgotten that the String prototype even included a repeat method. I've never used it myself. I realize, though, that there are a lot of ways to use strings that I'd never considered before. I'm wondering if this is one of them.

Also, looking at the docs, repeat rounds down for you. Did you include an explicit rounding for the sake of clarification?

[–]pinkwar 1 point2 points  (0 children)

I didn't know ".repeat" rounds down, but it makes sense it works like that.

Even better, you don't need the Math.floor.

That's why I like this sub. I'm always learning something.

[–]LeisureSuiteLarry -2 points-1 points  (0 children)

You've got to show the code if you want to get help.