13. Roman to Integer

来源:互联网 发布:罗盘指南针软件下载 编辑:程序博客网 时间:2024/06/05 14:24

问题描述:

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

https://leetcode.com/problems/roman-to-integer/description/


思路分析:将罗马数字转换为阿拉伯数字。罗马数字有几个基准数,基准数左边的小数相减,基准数右边的小数相加。我们使用栈和switch语句来实现。


代码:

class Solution {public:    int romanToInt(string s) {        int num = 0, top = 0,buf = 0;        char c;        stack <char>stk;        //push the Roman numeral into a stack;        for (int i = 0;i<s.length();i++){            stk.push(s[i]);        }        //convert Roman numeral to an integar;        while (!stk.empty()){            top = convert(stk.top());            if (top < buf){        // if the number is smaller than last one, we should minus it                num = num - top;                buf = top;            }            else                num = num + top;                buf = top;            stk.pop();        }        return num;            }    int convert(char c){// every number have its value        int n = 0;        switch(c){            case 'I':{                n = 1;                break;            }            case 'V':{                n = 5;                break;            }            case 'X':{                n = 10;                break;            }            case 'L':{                n = 50;                break;            }            case 'C':{                n = 100;                break;            }            case 'D':{                n = 500;                break;            }            case 'M':{                n = 1000;                break;            }        }        return n;    }};

时间复杂度: O(n) 


反思:对于栈的操作不熟啊,stack <type>neme初始化,不知道pop()是没有返回值的,而top()才是真的返回栈顶元素。switch语句还不熟,记得case要break,要用:,字符用‘’,字符串用“”。string的可以当成一个数组来操作。