[Leetcode] Roman to Integer

Source: Internet
Author: User

Topic given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999. Train of thought first, learn Roman numerals, reference Roman numerals Roman numerals are the oldest representation of numbers, more than 2000 years earlier than Arab arrays, and originate from Rome numbers as follows Symbol:
Basic characters I V X L C D M
corresponding Arabic numerals 1 5 10 50 100 500 1000
Count rule:
    1. The same number ligatures, the number represented is equal to the number that these numbers are added to, for example: III = 3
    2. The small number is to the right of the large number, and the number represented is equal to the number added to the number, for example: VIII = 8
    3. Small numbers, limited to (I, X, and C) to the left of large numbers, represented by numbers equal to large numbers minus decimals, for example: IV = 4
    4. In normal use, no more than three consecutive digits must be repeated.
    5. Draw a line on the top of a number, indicating that the number is enlarged by 1000 times times (the subject only takes into account 3999 or less, so this rule is not used)
Secondly, Roman numerals to Arabic numerals (within 3999): The Roman numerals are traversed backwards, and if a number is smaller than the previous one, the number is added. Conversely, subtract twice times the previous number and then add the number JS code:
varRomantoint =function(s) {vararray=[];  for(vari=0;i<s.length;i++){            varWord=s.substring (i,i+1); Switch(word) { Case"I": Array[i]=1;  Break;  CaseV: Array[i]=5;  Break;  CaseX: Array[i]=10;  Break;  CaseL: Array[i]=50;  Break;  CaseC: Array[i]=100;  Break;  CaseD: Array[i]=500;  Break;  CaseM: Array[i]=1000;  Break; }                        }        varResult=array[0];  for(varj=0;j< (array.length-1); J + +){            if(array[j+1]>Array[j]) {Result+ = (array[j+1]-array[j]*2)            }Else{result+=array[j+1]; }        }        returnresult; };

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