40ms C++ solution, 15 lines code


  • 2
    H
    class Solution {
    public:
    string intToRoman(int num) {
    	int nums[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
    	string roman[] = {"I", "IV", "V", "IX","X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
    	string res;
    	for(int i = 12; i>=0; ){
    		if(num>=nums[i]){
    			res += roman[i]; num -= nums[i];
    		}
    		else i--;
    	};
    	return res;
    }
    };

Log in to reply
 

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