Leetcode------Roman to Integer

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.