Is this solution acceptable for job interview?


  • 1
    Z
    class Solution {
    public:
    	void gen_str(string &s, int num, char one, char five, char ten)
    	{
    		switch (num)
    		{
    		case 1:
    			s += one;
    			break;
    		case 2:
    			s = s + one + one;
    			break;
    		case 3:
    			s = s + one + one+one;
    			break;
    		case 4:
    			s = s + one + five;
    			break;
    		case 5:
    			s += five;
    			break;
    		case 6:
    			s = s + five + one;
    			break;
    		case 7:
    			s = s + five + one + one;
    			break;
    		case 8:
    			s = s + five + one + one + one;
    			break;
    		case 9:
    			s = s + one + ten;
    			break;
    		}
    	}
    	string intToRoman(int num) {
    		int th = num / 1000 % 10;
    		int hu = num / 100 % 10;
    		int te = num / 10 % 10;
    		int on = num % 10;
    		string ret;
    		gen_str(ret, th, 'M', 'V', 'X');
    		gen_str(ret, hu, 'C', 'D', 'M');
    		gen_str(ret, te, 'X', 'L', 'C');
    		gen_str(ret, on, 'I', 'V', 'X');
    		return ret;
    	}
    };

  • 12
    S

    Why don't you do something like this:

      class Solution {
    public:
        string intToRoman(int num) {                
            for (int i = 0; i < int_dict.size(); i++) {
                if (int_dict[i] <= num)
                    return roman_dict[i] + intToRoman(num - int_dict[i]);
            }
            return "";
        }
    private:
        vector<int> int_dict {1000, 900, 500, 400, 100,
                              90, 50, 40, 10, 9, 5, 4, 1};
        vector<string> roman_dict {"M", "CM", "D", "CD", 
                              "C", "XC", "L", "XL", "X", 
                              "IX", "V", "IV", "I"};
    };
    

    There is no problem with your code ,although it gives a sense of amateurism.


  • 0
    A

    swapedoc, your code is concise and elegant but I wouldn't suggest writing such a code on a job interview. Professional production code has also to be efficient and easy to understand. Your code is very inefficient and it needs some time to comprehend it. For example an input number 8 requires 5(!) traversals of the array and 4 recursive calls.
    On the contrary, zqtndfj@sina.com's code has no such problems. It's very easy to understand and quite efficient. It's much more suitable for a real job interview.


Log in to reply
 

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