解题报告 13 Easy
程序员文章站
2022-01-15 12:00:04
...
https://leetcode.com/problems/roman-to-integer
public static int singleCharToInt(char ch) {
int num = 0;
switch (ch) {
case 'I':
num = 1;
break;
case 'V':
num = 5;
break;
case 'X':
num = 10;
break;
case 'L':
num = 50;
break;
case 'C':
num = 100;
break;
case 'D':
num = 500;
break;
case 'M':
num = 1000;
break;
}
return num;
}
public static int romanToInt(String s) {
if(s.length() ==1) return singleCharToInt(s.charAt(0));
int sum = 0,len = s.length();
for (int i = 0; i < len; i++) {
if(s.charAt(i) == 'I') {
if(i<len-1) {
if(s.charAt(i+1) == 'V') {
System.out.println("----IV");
sum += 4;
}else if(s.charAt(i+1) == 'X') {
System.out.println("----IX");
sum += 9;
}else {
sum += 1;
}
}else {
sum += singleCharToInt(s.charAt(i));
}
}
else if(s.charAt(i) == 'X') {
if(i<len-1) {
if(s.charAt(i+1) == 'L') {
sum += 40;
}else if(s.charAt(i+1) == 'C') {
sum += 90;
}else {
sum += 10;
}
}else {
sum += singleCharToInt(s.charAt(i));
}
}
else if(s.charAt(i) == 'C') {
if(i<len-1) {
if(s.charAt(i+1) == 'D') {
sum += 400;
}else if(s.charAt(i+1) == 'M') {
sum += 900;
}else {
sum += 100;
}
}else {
sum += singleCharToInt(s.charAt(i));
}
}
else {
sum += singleCharToInt(s.charAt(i));
}
}
return sum;
}
上一篇: 剑指offer面试题1
下一篇: JDK8新特性之Optional类
推荐阅读
-
【百度之星2014~初赛(第二轮)解题报告】JZP Set 博客分类: 百度之星 百度之星解题报告acmhdu
-
codeforces Round #260(div2) A解题报告
-
【SDOI2016Round1】【解题报告】
-
LeetCode_Easy心得:13. Roman to Integer (C语言)
-
codeforces Round #259(div2) B解题报告
-
Codeforces Round #271 (Div. 2) 解题报告_html/css_WEB-ITnose
-
Codeforces Round #262 (Div. 2)解题报告_html/css_WEB-ITnose
-
Codeforces Round #281 (Div. 2) 解题报告 A.B.C.D._html/css_WEB-ITnose
-
codeforces Round #275(div2) D解题报告
-
牛客编程巅峰赛S1第6场 - 黄金&钻石&王者 (解题报告)