Integer to Roman & Roman to Integer

来源:互联网 发布:淘宝卖耳环能卖不 编辑:程序博客网 时间:2024/04/29 02:12
class Solution {public:    const string romans[4][10] = {          {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},          {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},          {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},          {"", "M", "MM", "MMM", "", "", "", "", "", ""}      };    string intToRoman(int num) {        // Start typing your C/C++ solution below        // DO NOT write int main() function            int p=0;        string res="";        while (num>0) {            int n=num%10;            num/=10;            res=romans[p][n]+res;            p++;        }        return res;    }};

1/17/14:

greedy:

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

Roman to Integer

class Solution {public:    const string romans[4][10] = {          {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},          {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},          {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},          {"", "M", "MM", "MMM", "", "", "", "", "", ""}      };    int singleValue(char c) {        switch (c) {            case 'I': return 1;            case 'V': return 5;            case 'X': return 10;            case 'L': return 50;            case 'C': return 100;            case 'D': return 500;            case 'M': return 1000;        }    }    int romanToInt(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int res=0;        int i=0;        int pre=singleValue(s[0]);        for (; i<s.size(); i++) {            int now=singleValue(s[i]);            if (pre<now) {                res=res-2*pre+now;            }else {                res+=now;            }            pre=now;                    }        return res;    }};

1/17/14: traverse backwards, if current one is smaller than the previous one, subtract the current number form the result, otherwise, add it to the result.

class Solution {public:    int romanToInt(string s) {        map<char, int> m;        m['M'] = 1000;        m['D'] = 500;        m['C'] = 100;        m['L'] = 50;        m['X'] = 10;        m['V'] = 5;        m['I'] = 1;                int res=m[s[s.size()-1]];        for (int i=s.size()-2; i>=0; i--) {            if (m[s[i]]>=m[s[i+1]]) {                res +=m[s[i]];            }else {                res -=m[s[i]];            }        }        return res;    }};