class Solution {
public:
string intToRoman(int num) {
string ans, ch = { 'M','D','C','L','X','V','I' };
int x,count = 0,flag = 0,x_2;
for (int i = 1000; num != 0;) {
x = num / i;
if (flag == 1 && i >= 5) {//当除数为5的倍数时要看除以5过后的数为不为4或者9
x_2 = num / (i / 5);
if (x_2 == 4) {
ans.push_back(ch[count + 1]);
ans.push_back(ch[count]);
num -= x_2 * (i / 5);
continue;
}
else if (x_2 == 9) {
ans.push_back(ch[count + 1]);
ans.push_back(ch[count - 1]);
num -= x_2 * (i / 5);
continue;
}
}
for (int j = 0; j < x; j++)
ans.push_back(ch[count]);
num = num - x * i;
count++;
if (flag == 0)
i /= 2, flag = 1;
else
i /= 5, flag = 0;
}
return ans;
}
};
LeetCode 12. 整数转罗马数字
最新推荐文章于 2024-09-30 10:07:25 发布