| Title: |
Roman to Integer |
| Pass Rate: |
34.1% |
| Difficulty: |
Simple |
Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
The whole is not very difficult, that is, to convert a string of Roman numerals into Arabic, mainly to the understanding of Roman numerals. I don't know anything about the meaning of Roman numerals first:
| I |
1 |
| V |
5 |
| X |
10 |
| L |
50 |
| C |
100 |
| D |
500 |
| M |
1000 |
In general are from large to small writing, and then add the line, but there will be a few special, such as Iv:5, cd:400, and so on, these are small in front, large reduction can be,
So the idea is to deal with the string from the back forward, the overall order is i:[length-1]->[0], each time comparing the position I and the i+1 position, if I position <i+1 position then use and value minus I position, and so on. There is no robustness to consider, the topic has been said to be in the 1-3999 string. Only processing is empty when the return 0 on the line, the specific algorithm to see the code:
1 Public classSolution {2 Public intRomantoint (String s) {3Map<character,integer> map=NewHashmap<character,integer>();4Map.put (' I ', 1);5Map.put (' V ', 5);6Map.put (' X ', 10);7Map.put (' L ', 50);8Map.put (' C ', 100);9Map.put (' D ', 500);TenMap.put (' M ', 1000); One intLength=s.length (), result=0; A if(length==0)return0; -Result=map.get (S.charat (length-1)); -Length=length-2; the while(length>=0){ - if(Map.get (S.charat (length)) <map.get (S.charat (length+1))) - { -result-=Map.get (S.charat (length)); +length--; - } + Else{ Aresult+=Map.get (S.charat (length)); atlength--; - } - - - } - returnresult; in } -}
Leetcode------Roman to Integer