Leetcode 13. Roman to Integer(水)
Posted shanyr
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 13. Roman to Integer(水)相关的知识,希望对你有一定的参考价值。
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000
For example, two is written as II
in Roman numeral, just two one‘s added together. Twelve is written as, XII
, which is simply X
+ II
. The number twenty seven is written as XXVII
, which is XX
+ V
+ II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is 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, which is written as IX
. There are six instances where subtraction is used:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be 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: 58 Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
1 class Solution 2 public: 3 int romanToInt(string s) 4 int ans = 0; 5 int top = 0; 6 int len = s.length(); 7 while(top<len) 8 if(s[top]==‘M‘) 9 ans += 1000; 10 top++; 11 12 else if(s[top]==‘D‘) 13 ans += 500; 14 top++; 15 16 else if(s[top]==‘C‘) 17 if(s[top+1]==‘D‘) 18 ans += 400; 19 top+=2; 20 21 else if(s[top+1]==‘M‘) 22 ans +=900; 23 top+=2; 24 25 else 26 ans += 100; 27 top++; 28 29 30 else if(s[top]==‘L‘) 31 ans+=50; 32 top++; 33 34 else if(s[top]==‘X‘) 35 if(s[top+1]==‘C‘) 36 ans += 90; 37 top+=2; 38 39 else if(s[top+1]==‘L‘) 40 ans += 40; 41 top+=2; 42 43 else 44 ans += 10; 45 top++; 46 47 48 else if(s[top]==‘V‘) 49 ans+=5; 50 top++; 51 52 else if(s[top]==‘I‘) 53 if(s[top+1]==‘X‘) 54 ans += 9; 55 top+=2; 56 57 else if(s[top+1]==‘V‘) 58 ans += 4; 59 top+=2; 60 61 else 62 ans += 1; 63 top++; 64 65 66 67 return ans; 68 69 ;
以上是关于Leetcode 13. Roman to Integer(水)的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 13. Roman to Integer