您的位置:首页 > 其它

LeetCode 12-13:Integer to Roman&&Roman to Integer

2015-06-12 15:01 423 查看
Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

1~9: {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};

10~90: {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};

100~900: {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};

1000~3000: {"M", "MM", "MMM"}.

很常规的题。

public class Solution {
int romanToInt(String s) {
int ans = change(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
if (change(s.charAt(i-1)) < change(s.charAt(i)) ){
ans += change(s.charAt(i)) - 2 * change(s.charAt(i-1));
} else {
ans += change(s.charAt(i));
}
}
return ans;
}

int change(char ch) {
switch (ch) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
}
return 0;
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: