> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/string/13.-roman-to-integer.md).

# 13. Roman to Integer

![](/files/-MbLa3H1PEuBrKQHPp7g)

![](/files/-MbLa8_a8oN7yW_1OpYm)

time: O(n)

space: O(1)

```java
class Solution {
    public int romanToInt(String s) {
        int result = 0;
        for (int i = 0; i < s.length()-1;i++) {
            int pre = helper(s.charAt(i));
            int post = helper(s.charAt(i+1));
            if (pre < post) {
                result -= pre;
            } else {
                result += pre;
            }
        }
        result += helper(s.charAt(s.length() - 1));
        return result;
    }
    private int helper(char c) {
        switch(c) {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
        }    
        return -1;
    }
    
    /*
    private int helper(char c) {
        Map<Character, Integer> map = Map.of(
            'I', 1, 'V', 5, 'X', 10,
            'L', 50, 'C', 100, 'D', 500, 'M', 1000
        );
        return map.get(c);    
    }
    */
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/string/13.-roman-to-integer.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
