# Roman Numeral converter solution optimization

My request to freeCodeCamp to check the complexity of my code. highly optimized solution.

``````function convertToRoman(num) {
let result = "";

const arabicNum = [
["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],
];
let n = arabicNum.length;
//reversing an array
for (let i = 0; i < n / 2; i++) {
let temp = arabicNum[i];
arabicNum[i] = arabicNum[n - 1 - i];
arabicNum[n - i - 1] = temp;
}

let low = 0;
let high = arabicNum.length - 1;

while (num >= 0) {
low = 0; //initializing each time because it gets changed inside binary Search

// binarySearch
while (low <= high) {
let mid = Math.floor((low + high) / 2);

if (num > arabicNum[mid][1]) low = mid + 1;
else if (num < arabicNum[mid][1]) high = mid - 1;
else {
result += arabicNum[mid][0];
//as num gets equal to arabicNum[mid][1] it return from the function
return result;
}
}
result += arabicNum[high][0];
num = num - arabicNum[high][1];
}
}

convertToRoman(1006);
``````

I’m not sure I understand why you need a ‘binary search’?

I use binary search to decrease the runtime complexity.

But you shouldn’t have a search at all. Adding the search adds a lot of unneeded complexity.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.