C++不能像Python那样使用'c'*num
的形式,重复字符,老老实实减吧。
class Solution {
public:string intToRoman(int num) {string ans = "";int res = num;while (res != 0) {if (res >= 1000) {ans += 'M';res -= 1000;} else if (res >= 900) {ans += "CM";res -= 900;} else if (res >= 500) {ans += 'D';res -= 500;} else if (res >= 400) {ans += "CD";res -= 400;} else if (res >= 100) {ans += 'C';res -= 100;} else if (res >= 90) {ans += "XC";res -= 90;} else if (res >= 50) {ans += 'L';res -= 50;} else if (res >= 40) {ans += "XL";res -= 40;} else if (res >= 10) {ans += 'X';res -= 10;} else if (res >= 9) {ans += "IX";res -= 9;} else if (res >= 5) {ans += 'V';res -= 5;} else if (res >= 4) {ans += "IV";res -= 4;} else {ans += 'I';res -= 1;}}return ans;}
};