LeetCode 12 Integer to Roman
概述
https://leetcode.com/problems/integer-to-roman
解法
写的时候注意 while 里面那些判断是 >=
class Solution {
public:
string intToRoman(int num) {
string ans;
int numM = num / 1000;
ans += string(numM, 'M');
num -= numM * 1000;
vector<string> cfgs = {"IVX", "XLC", "CDM"};
int i = int(to_string(num).size()) - 1;
while (i != -1) {
int base = pow(10, i);
// < 1000
if (num >= 9 * base) {
num -= 9 * base;
ans += cfgs[i][0];
ans += cfgs[i][2];
}
// < 900
if (num >= 5 * base) {
num -= 5 * base;
ans += cfgs[i][1];
}
// < 500
if (num >= 4 * base) {
num -= 4 * base;
ans += cfgs[i][0];
ans += cfgs[i][1];
}
// make it < 100
int numM = num / base;
num -= numM * base;
ans += string(numM, cfgs[i][0]);
i --;
}
return ans;
}
};
Links: leetcode-12-integer-to-roman