Roman to Integer

Source: Internet
Author: User

Given a Roman numeral, convert it to an integer.

Input is guaranteed to being within the range from 1 to 3999.

Idea: Before always think the Roman numeral good trouble, a brush when see on headache do not want to do. After looking at the wiki, I feel really good. This problem directly to a valid Roman numerals, you can directly from the back to calculate, do not consider so many rules, in addition to small in the large front to use a large reduction, the others accumulate. Save the corresponding value with HashMap, then use a prev to save the next Roman numeral to compare the current.

Roman numerals ref:https://zh.wikipedia.org/wiki/%e7%bd%97%e9%a9%ac%e6%95%b0%e5%ad%97

 Public classSolution { Public intRomantoint (String s) {intRes=0; Map<Character,Integer> save=NewHashmap<character,integer>(); Save.put (' I ', 1); Save.put (' V ', 5); Save.put (' X ', 10); Save.put (' L ', 50); Save.put (' C ', 100); Save.put (' D ', 500); Save.put (' M ', 1000); intPrev=0;  for(intI=s.length () -1;i>=0;i--)        {            intCurrent=Save.get (S.charat (i)); if(current>=prev) {Res+=Current ; }            Else{res-=Current ; } prev=Current ; }        returnRes; }}

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.