[Leetcode OJ] 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.

 

The following is Baidu's explanation of the number of Rome:

 

My code:

1 class solution {2 public: 3 int romantoint (string s) {4 Map <char, int> conversion; 5 conversion. insert (make_pair ('I', 1); 6 conversion. insert (make_pair ('V', 5); 7 conversion. insert (make_pair ('x', 10); 8 conversion. insert (make_pair ('l', 50); 9 conversion. insert (make_pair ('C', 100); 10 conversion. insert (make_pair ('D', 500); 11 conversion. insert (make_pair ('M', 1000); 12 INT ans = 0; 13 for (unsigned I = 0; I <S. size (); I ++) 14 {15 if (s [I] = 'V' | s [I] = 'l' | s [I] = 'D ') // do not place any of the basic numbers V, L, and D as decimal places on the left of the large number. The subtraction method is used to constitute the number of 16 ans + = Conversion [s [I]; 17 else // any one of the basic numbers I, X, and C can constitute the number itself, or the number can be larger than three on the right of a large number;Only one18 {19 if (I <S. size ()-1 & Conversion [s [I] <conversion [s [I + 1]) 20 {21 ans + = Conversion [s [I + 1]-conversion [s [I]; 22 I ++; 23} 24 else25 ans + = Conversion [s [I]; 26} 27} 28 return ans; 29} 30 };

 

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.