Roman to Integer

Source: Internet
Author: User

Roman numerals is represented by seven different symbols:,,,, I V , and X L C D M .

Symbol       valuei             1V             5X             10L             50C             100D             500M             1000

For example, the written as in II Roman numeral, and the just, the added together. Twelve is written as, XII and which is simply X + II . The number twenty seven XXVII is written as and which is XX + V + II .

Roman numerals is usually written largest to smallest from left to right. However, the numeral for four are not IIII . Instead, the number four is written as IV . Because the one is before the five we subtract it making four. The same principle applies to the number nine, and which is written as IX . There is six instances where subtraction is used:

    • ICan be placed before V (5) and X (Ten) to make 4 and 9.
    • Xcan be placed before () and (+) to make and L C 90.
    • CCan be placed before D () and (+) to make and M 900.

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

Example 1:

Input: "III" Output:3

Example 2:

Input: "IV" Output:4

Example 3:

Input: "IX" Output:9

Example 4:

Input: "LVIII" output:58explanation:l = v= 5, III = 3.

Example 5:

Input: "MCMXCIV" output:1994explanation:m = +, CM =/-, XC = all and IV = 4.
//time:o (n), Space:o (1)
Note: Since I stop is in the penultimate position, I jump out of the loop and add the last one
Public intRomantoint (String s) {if(s = =NULL|| S.length () = = 0) { return0; } intresult = 0; for(inti = 0; I <s.length ()-1; i++) { intCur =Map (S.charat (i)); intNext = Map (S.charat (i + 1))); if(cur >=next) {Result+=cur; } Else{ result -= cur; } } returnResult +Map (S.charat (S.length ()-1)); } Private intMapCharc) {Switch(c) { Case' I ' : return1; CaseV : return5; CaseX : return10; CaseL : return50; CaseC : return100; CaseD : return500; CaseM : return1000; default: return0; } }

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.