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.
这一道题的思路是,先把特殊情况表现在结果里。然后再将字符串转化为字符串数组,用for循环得出最后的结果。
从题目中可以看出,当I, X, C放在其他数前面的时候,他们代表的是减去自己的数值。因为在后面for循环的过程中,它们还要被加一遍自己的值,所以在一开始的时候应该减去两倍的自己的值。
需要将字符串转化为字符串数组的原因是,indexOf()只能判断字符串中有没有这个字符,不能判断出现了几次。而在罗马数字中,一个字符可能出现多次。但是在罗马数字中“IV”,“IX”这些特殊情况不可能相同的情况在一个字符串中出现两次,所以在计算特殊情况的时候可以用indexOf()。
1 class Solution { 2 public int romanToInt(String s) { 3 int sum=0; 4 if(s.indexOf("IV")!=-1) sum=sum-2; 5 if(s.indexOf("IX")!=-1) sum=sum-2; 6 if(s.indexOf("XL")!=-1) sum=sum-20; 7 if(s.indexOf("XC")!=-1) sum=sum-20; 8 if(s.indexOf("CD")!=-1) sum=sum-200; 9 if(s.indexOf("CM")!=-1) sum=sum-200; 10 11 char[] arr=s.toCharArray(); 12 for(int i =0;i<s.length();i++){ 13 if(arr[i]==‘I‘) sum=sum+1; 14 if(arr[i]==‘V‘) sum=sum+5; 15 if(arr[i]==‘X‘) sum=sum+10; 16 if(arr[i]==‘L‘) sum=sum+50; 17 if(arr[i]==‘C‘) sum=sum+100; 18 if(arr[i]==‘D‘) sum=sum+500; 19 if(arr[i]==‘M‘) sum=sum+1000; 20 } 21 return sum; 22 } 23 }
这道题主要用了两个字符串函数 indexOf() 和 toCharArray()。
indexOf() 方法在字符串中查找子字符串出现的位置,如过存在返回字符串出现的位置(第一位为0),如果不存在返回 -1。
toCharArray() 方法将字符串转化为字符串数组。如果原字符串中有分隔符,例如逗号,空格等,可以用split(string) 方法将字符串通过指定分隔符分割为数组。
原文地址:https://www.cnblogs.com/bbcxnz96/p/10184104.html