C/C++solution,Calculate from the back forward


  • 0
    _
    class Solution {
    public:
        int romanToInt(string s) {
            int len = s.length();
            int i;
            int temp_max = 0;
            int ans = 0;
            int num;
            for(i=len-1;i>=0;i--)
            {
                switch(s[i])
                {
                case 'I':
                    num = 1;
                    break;
                case 'X':
                    num = 10;
                    break;
                case 'C':
                    num = 100;
                    break;
                case 'M':
                    num = 1000;
                    break;
                case 'V':
                    num = 5;
                    break;
                case 'L':
                    num = 50;
                    break;
                case 'D':
                    num = 500;
                    break;
                default:
                    num = 0;
                    break;
                }            
                if(num >= temp_max)
                {
                    temp_max = num;
                    ans = ans + num;
                }
                else
                {
                    ans = ans - num;
                }
                printf("[%d][%d]--",num,ans);
            }
            return ans;  
        }
    };
    

Log in to reply
 

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