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.


Topic Analysis: The topic seems relatively simple but behind the hidden many of the rules of the Roman numerals, access to some information the main rules are as follows

Roman Numeral Rules:

1, a total of 7 Roman numerals, namely I (1), V (5), X (10), L (50), C (100), D (500) and M (1000). There is no "0" in Roman numerals.

2, repetition: a Roman numeral repeats up to 3 times.

3, right plus left minus:

The smaller Roman numerals on the right side of the larger Roman numerals indicate large numbers plus small numbers.

The smaller Roman numerals on the left of the larger Roman numerals indicate that large numbers decrease the numbers.

4, the left minus the number has a limit, limited to I, X, C, and placed on the left of large numbers can only use one.

(*) The small digits to the left of V and X can only be used with Ⅰ.

(*) The small digits to the left of L and C can only be used with X.

(*) The small numbers on the left of D and M can only be used in C.

That's a good question to solve.

Algorithm analysis: Mainly through the hash table mapping, the other is very simple, on the AC code

public int Romantoint (String s) {//Security judgment if (s = = NULL | | s.length () = = 0) return 0;//hash table Hashmap<character, INTEGER&G T Nummap = new Hashmap<character, integer> () nummap.put (' I ', 1); Nummap.put (' V ', 5); Nummap.put (' X ', +); nummap.put (' L ', +); Nummap.put (' C ', +); Nummap.put (' D ', ' n '); Nummap.put (' M ', "n"); int len = S.length (); int result = Nummap.get (s . CharAt (Len-1)); for (int i = len-2; I >= 0; i--) {//Compare Roman characters if (Nummap.get (S.charat (i + 1)) <=nummap.get (S.charat (i)) {result = result + Nummap.get (S.charat (i));} else {result = Result-nummap.get (S.charat (i));}} return result;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.