Mismatch with the output of here and VS


  • 0
    D
    	int RomanValue(char c) {
    	switch (c) {
    	case 'I':
    		return 1;
    		break;
    	case 'V':
    		return 5;
    		break;
    	case 'X':
    		return 10;
    		break;
    	case 'L':
    		return 50;
    		break;
    	case 'C':
    		return 100;
    		break;
    	case 'D':
    		return 500;
    		break;
    	case 'M':
    		return 1000;
    		break;
    	}
    }
    
    int romanToInt(string s) {
    	int res = 0;
    	unsigned int left, right;
    	if (s.length() == 1) return RomanValue(s[0]);
    	/* - Some notes: if input is like XXVI, we first check the left of the index, then the right.
    	   - There will be some special cases handled. These are as follows (from wikipedia):
    
    		   "The numeral I can be placed before V and X to make 4 units (IV) and 9 units (IX) respectively
    		    X can be placed before L and C to make 40 (XL) and 90 (XC) respectively
    		    C can be placed before D and M to make 400 (CD) and 900 (CM) according to the same pattern"
    	*/
    	for (left = 0, right = 1; left < s.length() && right < s.length(); left++, right++) {
    		if ((s[left] == 'I' && (s[right] == 'V' || s[right] == 'X') || 
    			s[left] == 'X' && (s[right] == 'L' || s[right] == 'C') || 
    			s[left] == 'C' && (s[right] == 'D' || s[right] == 'M'))) {
    
    			res += RomanValue(s[right]) - RomanValue(s[left]);
    			// so this was the case. For example, if number was CMIX (909), my left is C and right is M. Then, I need to skip this duo.
    			left++; right++;
    		}
    		else
    			res += RomanValue(s[left]);
    	}
    	// If right has gone out of bounds, that means left is at end index.
    	if (right >= s.length()) res += RomanValue(s[left]);
    	return res;
    }
    

    Mismatching output at 1884, which is MDCCCLXXXIV. I get this correct answer when I compile and execute from Visual Studio Express but not in here. Any ideas? (A screenshot to show that it really does: https://www.dropbox.com/s/rrkv5hv27i63pqb/Mismatch.png?dl=0)


  • 0
    D
    		// If right has gone out of bounds, that means left is at end index. However, if the last piece is a duo, left is also out of bounds.
    	if (right >= s.length() && left == s.length() - 1) res += RomanValue(s[left]);
    

    Problem solved. The last was a duo, so left was out of bounds as well.


Log in to reply
 

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