LeetCode 13. Roman to Integer
原题链接在这里:https://leetcode.com/problems/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.
题解:
取当前char得到的数值若是比之前的小,就正常加上当前数值,若是比之前位大说明刚才加错了,需要先减掉再加上(cur-pre).
e.g. "XIV", at the beginning, res = 10. When i = 1, cur = 1, pre = 10, cur<pre, res = 11; when i = 2, cur = 5, pre = 1, cur>pre, res = 11-1+(5-1) = 14. 若是cur==pre,正常加cur, "XX" = 20.
Time Complexity: O(s.length()). Space: O(1).
AC Java:
1 public class Solution { 2 public int romanToInt(String s) { 3 if(s == null || s.length() == 0){ 4 return 0; 5 } 6 7 int res = getValue(s.charAt(0)); 8 for(int i = 1; i<s.length(); i++){ 9 int pre = getValue(s.charAt(i-1)); 10 int cur = getValue(s.charAt(i)); 11 if(cur >pre){ 12 res = res-pre + (cur-pre); 13 }else{ 14 res += cur; 15 } 16 } 17 return res; 18 } 19 20 private int getValue(char c){ 21 int res = 0; 22 switch(c){ 23 case 'I': 24 res = 1; 25 break; 26 case 'V': 27 res = 5; 28 break; 29 case 'X': 30 res = 10; 31 break; 32 case 'L': 33 res = 50; 34 break; 35 case 'C': 36 res = 100; 37 break; 38 case 'D': 39 res = 500; 40 break; 41 case 'M': 42 res = 1000; 43 break; 44 default: 45 res = 0; 46 } 47 return res; 48 } 49 }