8000 data-structure-agorithms-in-js/133.md at master · kalpeshsingh/data-structure-agorithms-in-js · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
69 lines (54 loc) · 2.36 KB

File metadata and controls

69 lines (54 loc) · 2.36 KB

Solution

Submission link - https://bigfrontend.dev/problem/roman-numerals-to-integer/discuss/650

/**
 * @param {string} str - roman numeral string
 * @returns {number} integer
 */
function romanToInteger(str) {

  // keep value of 7 symbols
  const symbolMapper = {
    "I": 1,
    "V": 5,
    "X": 10,
    "L": 50,
    "C": 100,
    "D": 500,
    "M": 1000
  };

  // we will keep adding/substracting number based on condition
  // so we need to begin with 0
  let result = 0;

  // iterate over the string to convert it to the number 
  for(let i =0; i < str.length; i++) {

    const symbolValue = symbolMapper[str.charAt(i)]; // first char value
    const nextSymbolValue = symbolMapper[str.charAt(i+1)]; // next char value
    const lastChar = str.length - 1; // last char (there is no next char when we hit last char)

    // as per rule describe in problem
    // there is no next char to compare when we hit last char so we just add it
    if((symbolValue >= nextSymbolValue) || (i == lastChar)) { 
      result += symbolValue;
    } else {
      result -= symbolValue;
    }
  }
  return result;
}

Short story

The algorithm is already given in the problem so it was easy to solve this problem.

Algorithm (Binary Search)

Symbols are listed from highest to lowest, from left to right

  1. If the next symbol value is bigger than the current one, it means subtracting, otherwise adding.

Code overview

  1. As roman numbers have only 7 symbols, we will keep them with their corresponding values in an Object. Feel free to use a fancy Map or Set.
  2. We will declare a result variable with an initial value of 0
    1. Why 0? Because we need to subtract and add values based on condition. So the beginning condition must be 0.
  3. We will loop over the roman string.
  4. We will define and declare current symbol value symbolValue, next symbol value nextSymbolValue and also keep last char lastChar
  5. As per the algorithm, we check if symbolValue >= nextSymbolValue then we will symbolValue in the result
  6. Else we will subtract from the result
  7. In case, we hit last char in roman string and there is nothing to compare then we add lastChar symbol value
  8. We finally return the result

I'm excited to improve the solution and code walkthrough. Feel free to drop a comment, or send a PR or send memes @knowkalpesh.

0