description:
把阿拉伯数字转换成罗马数字
Note:
Example 1:
Input: 3
Output: "III"
Example 2:
Input: 4
Output: "IV"
Example 3:
Input: 9
Output: "IX"
Example 4:
Input: 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
Example 5:
Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
my answer:
大佬的answer:真的在leetcode里写代码的时候要时刻注意还是不是英文半角,要不然真的崩溃,哪出错都不知道
class Solution {
public:
string intToRoman(int num) {
string res = "";
vector<int> value = {1000, 500, 100, 50, 10, 5, 1};
vector<char> roman = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
for(int n = 0; n < 7; n += 2){
int x = num / value[n];
if (x < 4){
for (int i = 1; i <= x; i++) res += roman[n];
}
else if(x == 4){
res = res + roman[n] + roman[n - 1];
}
else if(x > 4 && x < 9){
res += roman[n - 1];
for (int i = 6; i <= x; i++) res += roman[n];
}else if(x == 9){
res = res + roman[n] + roman[n -2];
}
num %= value[n];
}
return res;
}
};
relative point get√:
hint :
在4和9处讨论好分割点,其实比较easy辣,思路逻辑神马的都还ok。