[Leetcode] [Java] Roman to Integer

Source: Internet
Author: User

Topic:

Given a Roman numeral, convert it to an integer.

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


Test instructions

Given a Roman number, convert it to an integer.

The given input is guaranteed to be between 1-3999


Algorithm Analysis:


* 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:

* Lower Roman numerals on the right side of the larger Roman numerals, indicating large numbers plus small numbers.

* On the left of the larger Roman numerals, the smaller Roman numerals indicate that large numbers decrease the numbers.


AC Code:

public class solution{    private  int sss;    public  int Romantoint (String s)    {      map<character, integer> dct=new hashmap<character, Integer > ();      Dct.put (' I ', 1);       Dct.put (' I ', 1);       Dct.put (' V ', 5);       Dct.put (' V ', 5);       Dct.put (' X ', ten);       Dct.put (' x ', ten);       Dct.put (' L ', +);       Dct.put (' l ', +);       Dct.put (' C ', +);       Dct.put (' C ', +);       Dct.put (' D ', +);       Dct.put (' d ', +);      Dct.put (' M ', +);       Dct.put (' m ', +);       int sum = 0, J;      for (int i = 0; i < s.length (); ++i)      {          j = i+1;          if (J < s.length () && Dct.get (S.charat (j)) > Dct.get (S.charat (i)))          {            sum + = Dct.get (S.charat (j) )-Dct.get (S.charat (i));            i = j;          }          else            sum + = Dct.get (S.charat (i));      }      return sum;    }}


Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

[Leetcode] [Java] Roman to Integer

Related Article

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.