[LeetCode] Roman to Integer, leetcoderoman

Source: Internet
Author: User

[LeetCode] Roman to Integer, leetcoderoman

Given a roman numeral, convert it to an integer.

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

This question mainly involves figuring out the algorithm for turning Roman into Integer.

Remember that if a number is smaller than the previous one, it will be used as a plus number, and vice versa, it will be used as a reduction. (Eg: IV = 4, XLV = 45, XX = 20)

Therefore, we can start from the end of the team and slowly determine whether a number should be + or -.

The Code is as follows .~

public class Solution {    public int romanToInt(String s) {        if(s==null||s.length()==0){            return 0;        }        HashMap<Character,Integer> hash=new HashMap<Character,Integer>();        hash.put('I',1);        hash.put('V',5);        hash.put('X',10);        hash.put('L',50);        hash.put('C',100);        hash.put('D',500);        hash.put('M',1000);        int len=s.length();        int result=hash.get(s.charAt(len-1));        int compare=result;        for(int i=len-2;i>=0;i--){            int curr=hash.get(s.charAt(i));            if(curr>=compare){                result=result+curr;            }else{                result=result-curr;            }            compare=curr;        }        return result;    }}

 

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.