LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Question:

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

Ideas:

Map the key values, and then the n-1 bits are scanned to The 0th bits.

package manipulation;import java.util.HashMap;public class RomanToInteger {    public int romanToInt(String s) {        int len = 0;        if (s == null || (len = s.length()) == 0) return 0;        HashMap<Character, Integer> map = new HashMap<Character, Integer>();        map.put('I', 1);        map.put('V', 5);        map.put('X', 10);        map.put('L', 50);        map.put('C', 100);        map.put('D', 500);        map.put('M', 1000);        int res = map.get(s.charAt(len - 1));        for (int i = len - 2; i >= 0; --i) {            if (map.get(s.charAt(i + 1)) > map.get(s.charAt(i)))                res -= map.get(s.charAt(i));            else                res += map.get(s.charAt(i));        }                return res;    }        public static void main(String[] args) {        // TODO Auto-generated method stub        RomanToInteger r = new RomanToInteger();        System.out.println(r.romanToInt("MCM"));    }}

 

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.