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.

Given a roman number, convert it into an integer.

Convert a string of numbers to a character array. In the following table, each number corresponds to only one character, and the characters are different. Therefore, the values can be matched from the beginning.

The Roman Symbols

The Romans used a special method of showing numbers, based on the following symbols:

1 5 10 50 100 500 1000
I V X L C D M
public int romanToInt(String s) {Map
 
   romans = new HashMap
  
   ();romans.put('I', 1);romans.put('V', 5);romans.put('X', 10);romans.put('L', 50);romans.put('C', 100);romans.put('D', 500);romans.put('M', 1000);char[] ch = s.toCharArray();int num = 0, val = 0;for (int i = 0; i < ch.length; i++) {val = romans.get(ch[i]);if (i == ch.length - 1 || romans.get(ch[i + 1]) <= val)num += val;elsenum -= val;}return num;}
  
 

Reference: http://www.mathsisfun.com/roman-numerals.html

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.