[Leetcode questions and Notes] 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.

 

Question: Conversion Method: scan the Rome character from left to right. If the number corresponding to the current character is smaller than the previous one, add the number directly; otherwise, add this number and subtract twice the previous number, and then update the previous number. Use a hashmap to store the correspondence between Roman characters and numbers.

See http://www.cnblogs.com/sunshineatnoon/p/3856057.html

For example, the Rome digital dcxix: 500 + 100 + 10 + 1 + 10-2 = 619

The Code is as follows:

 1 public class Solution { 2     public int romanToInt(String s) { 3         if(s == null || s.length() == 0) 4             return 0; 5          6         HashMap<Character, Integer> map= new HashMap<Character,Integer>(); 7         map.put(‘I‘, 1); 8         map.put(‘V‘, 5); 9         map.put(‘X‘, 10);10         map.put(‘L‘, 50);11         map.put(‘C‘, 100);12         map.put(‘D‘, 500);13         map.put(‘M‘, 1000);14         15         int length = s.length();16         int result = map.get(s.charAt(0));17         int last = result;18         19         for(int i = 1;i < length;i++){20             int temp = map.get(s.charAt(i));21             if(temp <= last)22                 result += temp;23             else24                 result = result + temp - 2*last;25             last = temp;26         }27         28         return result;29     }30 }

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.