[Leetcode] Roman to integer

Source: Internet
Author: User

Given a roman numeral, convert it to an integer.

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

 

Solution:

The question is to convert the roman numerals into numbers.

First, let's take a look at the number of Rome. refer to the number of Rome. The number of Rome is the oldest digital representation, more than 2000 years earlier than that of the Arabic array. The number originating from Rome has the following symbols:
Basic Characters I V X L C D M
Corresponding to Arabic numerals 1 5 10 50 100 500 1000
Counting rules:
  1. If the numbers are the same, the numbers are equal to the total number of the numbers, for example, III = 3.
  2. A small number is on the right of a large number, and the number is equal to the sum of the numbers, for example, VIII = 8.
  3. A small number is limited to (I, X, and c) on the left side of a large number. The number is equal to a large number minus the number of decimal places. For example: IV = 4
  4. During normal use, the number must be repeated no more than three times.
  5. Draw a horizontal line on a number, indicating that the number is increased by 1000 times (this question only considers the number within 3999, so this rule is not used)
Second, the rule for conversion of Roman numerals to Arabic numerals (limited to less than 3999): traverses the roman numerals from the front to the back. If a number is smaller than the last one, this number is subtracted. Otherwise, add this number.
 1 public class Solution { 2     public int romanToInt(String s) { 3         HashMap<Character, Integer> hm=new HashMap<Character, Integer>(); 4         hm.put(‘M‘, 1000); 5         hm.put(‘D‘, 500); 6         hm.put(‘C‘, 100); 7         hm.put(‘L‘, 50); 8         hm.put(‘X‘, 10); 9         hm.put(‘V‘, 5);10         hm.put(‘I‘, 1);11         int result=0;12         for(int i=0;i<s.length()-1;i++){13             if(hm.get(s.charAt(i))

 

[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.