Solution code - class Solution { public: int helper(int num, string &ans) { int quo; if (num>=1000) { quo = num/1000; num %= 1000; while(quo-- > 0) { ans += "M"; } } else if (num>=900) { ans += "CM"; num -= 900; } else if (num>=500) { ans += "D"; num -= 500; } else if (num>=400) { ans += "CD"; num -= 400; } else if (num>=100) { quo = num/100; num %= 100; while(quo-- > 0) { ans += "C"; } } else if (num>=90) { ans += "XC"; num -= 90; } else if (num >= 50) { ans += "L"; num -= 50; } else if (num >= 40) { ans += "XL"; num -= 40; } else if (num >= 10) { quo = num/10; num %= 10; while(quo-- > 0) { ans += "X"; } } else if (num >=9) { ans += "IX"; num -= 9; } else if (num >= 5) { ans += "V"; num -= 5; } else if (num >= 4) { ans += "IV"; num -= 4; } else { quo = num; num = 0; while(quo-- > 0) { ans += "I"; } } return num; } string intToRoman(int num) { string ans; while(num) { num = helper(num, ans); } return ans; } };
Solution code - class Solution {
public:
int helper(int num, string &ans) {
int quo;
if (num>=1000) {
quo = num/1000;
num %= 1000;
while(quo-- > 0) {
ans += "M";
}
} else if (num>=900) {
ans += "CM";
num -= 900;
} else if (num>=500) {
ans += "D";
num -= 500;
} else if (num>=400) {
ans += "CD";
num -= 400;
} else if (num>=100) {
quo = num/100;
num %= 100;
while(quo-- > 0) {
ans += "C";
}
} else if (num>=90) {
ans += "XC";
num -= 90;
} else if (num >= 50) {
ans += "L";
num -= 50;
} else if (num >= 40) {
ans += "XL";
num -= 40;
} else if (num >= 10) {
quo = num/10;
num %= 10;
while(quo-- > 0) {
ans += "X";
}
} else if (num >=9) {
ans += "IX";
num -= 9;
} else if (num >= 5) {
ans += "V";
num -= 5;
} else if (num >= 4) {
ans += "IV";
num -= 4;
} else {
quo = num;
num = 0;
while(quo-- > 0) {
ans += "I";
}
}
return num;
}
string intToRoman(int num) {
string ans;
while(num) {
num = helper(num, ans);
}
return ans;
}
};