Short 28ms C++, non-enumerate


  • 0
    V
    class Solution {
    public:
        string intToRoman(int num) {
    		string ans;
    		int digit;
    
    		digit = num / 1000; num = num % 1000;
    		ans = string(digit, 'M');
    
    		helper(ans, num/100, "CM", "D", "CD", 'C');
    		num = num % 100;
    		helper(ans, num/10, "XC", "L", "XL", 'X');
    		num = num % 10;
    		helper(ans, num, "IX", "V", "IV", 'I');
    
    		return ans;
        }
    
    private:
    	void helper(string& ans, int digit, string nine, string five, string four, char one) {
    		if (digit == 9) {ans += nine;}
    		else {
    			if (digit >= 5) {ans += five; digit -= 5;}
    			if (digit == 4) {ans += four;}
    			else {ans += string(digit, one);}
    		}
    	}
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.