"Simple Algorithm" 43. Roman numerals to integers

Source: Internet
Author: User

Topic:

The Roman numerals contain the following seven characters: I, V, X, L,c,d and M. Character value I1V5XTenL -C -D -M +For example, Roman numerals2Write II, which is two parallel1。 AWrite XII, which is X + II. -Write as XXVII, which is XX + V +II. Usually, the number of Roman numerals is small and the numbers are on the right side of the large numbers. But there are exceptions, such as4Do not write IIII, but IV. Digital1In the digital5The left side, the number represented is equal to the large number5Decrease number1The resulting value4。 Similarly, the number9represented as IX. This special rule only applies to the following six cases: I can be placed in V (5) and X (Ten) to the left, to indicate4And9. X can be placed in L ( -) and C ( -) to the left, to indicate +And -. C can be placed in D ( -) and M ( +) to the left, to indicate -And the. Given a Roman number, convert it to an integer. Input ensures that the1To3999within the range. Example1: Enter:"III"Output:3Example2: Enter:"IV"Output:4Example3: Enter:"IX"Output:9Example4: Enter:"LVIII"Output: -Explanation: C= -, L = -, XXX = -, III =3. Example5: Enter:"MCMXCIV"Output:1994Explanation: M= +, CM = the, XC = -, IV =4.

Code implementation:

classSolution { Public:    intRomantoint (strings) {inttagval[ the]; tagval['I'] =1; tagval['V'] =5; tagval['X'] =Ten; tagval['C'] = -; tagval['M'] = +; tagval['L'] = -; tagval['D'] = -; intval =0;  for(inti =0; I < s.length (); i++){              if(i+1>= s.length () | | tagval[s[i+1]] <=Tagval[s[i]) Val+=Tagval[s[i]]; ElseVal-=Tagval[s[i]]; }          returnVal; }};

"Simple Algorithm" 43. Roman numerals to integers

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.