Home > Web Front-end > JS Tutorial > LeetCode: Roman Numeral to Integer

LeetCode: Roman Numeral to Integer

Mary-Kate Olsen
Release: 2024-12-17 17:38:18
Original
981 people have browsed it

LeetCode: Roman Numeral to Integer

Roman numerals are an ancient number system that still finds use today. Converting them to regular integers is a common programming challenge. Let's break down a solution that elegantly handles this conversion.

The Roman Numeral System

Before diving into the code, let's understand how Roman numerals work:

  • Basic symbols: I (1), V (5), X (10), L (50), C (100), D (500), M (1000)
  • Numbers are generally written largest to smallest, left to right
  • When a smaller number comes before a larger one, it means subtraction

The Solution

function romanToInteger(str) {
  let symbols = {
    I: 1,
    V: 5,
    X: 10,
    L: 50,
    C: 100,
    D: 500,
    M: 1000,
  }

  let result = 0

  for (let i = 0; i < str.length; i++) {
    const current = str[i]
    const next = str[i + 1]

    if (symbols[current] < symbols[next]) {
      result -= symbols[current]
    } else {
      result += symbols[current]
    }
  }

  return result
}

Copy after login

How It Works: Step by Step

1. Symbol Mapping
First, we create an object that maps each Roman numeral to its corresponding integer value. This makes it easy to look up values quickly.

2. Iterating Through the String
We loop through each character in the input string, keeping track of both the current character and the next one.

3. The Core Logic
For each character, we compare its value with the next character's value:

  • If the current value is less than the next value, we subtract it (handles cases like IV = 4)
  • Otherwise, we add it to our result (handles cases like VI = 6)

Examples

romanToInteger("III") → 3
Each I adds 1 to the result

romanToInteger("IV") → 4
I is subtracted because it's less than V

romanToInteger("IX") → 9
I is subtracted because it's less than X

Conclusion

This solution elegantly handles the conversion of Roman numerals to integers by using a simple comparison technique. The code is concise yet powerful enough to handle all valid Roman numeral inputs.

The above is the detailed content of LeetCode: Roman Numeral to Integer. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template