【LeetCode算法-13】Roman to Integer

时间:2021-09-14 03:28:25

LeetCode第13题

Roman numerals are represented by seven different symbols: IVXLCD 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 before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (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: C = 100, L = 50, XXX = 30 and III = 3.

Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

废话不多说,直接上代码,姿势一定要好看

class Solution {
private int[] num;
public int romanToInt(String s) {
//先将罗马字母转为数字
stringToNum(s);
//检查左小右大的情况
checkLeftDigit();
//求和
int sum = 0;
for(int l = 0;l<num.length;l++){
sum+=num[l];
}
return sum;
} public void stringToNum(String s){
num = new int[s.length()];
for(int i=0;i<s.length();i++){
switch(s.charAt(i)){
case 'I':
num[i]=1;
break;
case 'V':
num[i]=5;
break;
case 'X':
num[i]=10;
break;
case 'L':
num[i]=50;
break;
case 'C':
num[i]=100;
break;
case 'D':
num[i]=500;
break;
case 'M':
num[i]=1000;
break;
default:
num[i]=0;
break;
}
}
} public void checkLeftDigit(){
for(int j = 0;j<num.length;j++){
for(int k = j+1;k<num.length;k++){
if(num[j]==1 &&(num[k]==5 || num[k]==10)){
num[j] *= (-1);
}else if(num[j]==10 &&(num[k]==50 || num[k]==100)){
num[j] *= (-1);
}else if(num[j]==100 &&(num[k]==500 || num[k]==1000)){
num[j] *= (-1);
}
}
}
}
}

1.因为是手写,api会写错,String的长度是length()不是length;数组的长度是length不是size()

2.一开始我考虑会不会有IXC(109?91?89?)的情况,后来审题发现罗马字母正常情况左大右小,何况109是CIX,91是XCI,89是LXXXIX;所以不会有IXC的情况,就不用判断了

3.其实Char也能通过ASCII来判断大小和差值,不过最后还是要转成INT相加,所以我就先转成INT了