Simple C solution


  • 0
    V
    int romanToInt(char * s) 
    {
    	int ret, curr, last, * nums, size, i;
        
    	size = strlen(s);
    	nums = (int *)malloc(size * sizeof(*nums));
    	
    	// translate to integers
    	for (i = 0; i < size; ++i)
    	{
    		switch (tolower(s[i]))
    		{
    			case 'i': nums[i] = 1; break;
    			case 'v': nums[i] = 5; break;
    			case 'x': nums[i] = 10; break;
    			case 'l': nums[i] = 50; break;
    			case 'c': nums[i] = 100; break;
    			case 'd': nums[i] = 500; break;
    			case 'm': nums[i] = 1000; break;
    		}
    	}
    	
    	ret = curr = last = 0;
    	// start from the back
    	for (i = size - 1; i >= 0; --i)
    	{
    		curr = nums[i];
    		
    		if (curr < last)
    			ret -= curr;
    		else
    			ret += curr;
    		
    		last = curr;
    	}
    	free(nums);
    	
    	return ret;
    }
    

Log in to reply
 

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