LeetCode刷題記錄——day5

想成为编程高手的阿曼發表於2024-03-23

1、https://leetcode.cn/problems/roman-to-integer/solutions/1/bao-li-po-jie-by-a-studentdog-s1va/?envType=study-plan-v2&envId=top-interview-150
關鍵在於建立字典

class Solution {
public:
    int romanToInt(string s) {
        unordered_map<string, int> m = {{"I", 1}, {"IV", 3}, {"IX", 8}, {"V", 5}, {"X", 10}, {"XL", 30}, {"XC", 80}, {"L", 50}, {"C", 100}, {"CD", 300}, {"CM", 800}, {"D", 500}, {"M", 1000}};
        int r = m[s.substr(0, 1)];
        for(int i=1; i<s.size(); ++i){
            string two = s.substr(i-1, 2);
            string one = s.substr(i, 1);
            r += m[two] ? m[two] : m[one];
        }
        return r;
    }
};

2、https://leetcode.cn/problems/integer-to-roman/?envType=study-plan-v2&envId=top-interview-150
暴力計算即可,記得向下取整的問題

class Solution {
public:
    string intToRoman(int num) {
        int len=0,i=0;
        string s;
        len = num/1000;
        num=num%1000;
        for(;i<len;i++){
            s+='M';
        }

        len=len+2*(num/900);
        num=num%900;
        for(;i<len;i=i+2){
            s+='C';
            s+='M';
        }

        len=len+num/500;
        num=num%500;
        for(;i<len;i++){
            s+='D';
        }

        len=len+2*(num/400);
        num=num%400;
        for(;i<len;i=i+2){
            s+='C';
            s+='D';
        }

        len=len+num/100;
        num=num%100;
        for(;i<len;i++){
            s+='C';
        }

        len=len+2*(num/90);
        num=num%90;
        for(;i<len;i=i+2){
            s+='X';
            s+='C';
        }

        len=len+num/50;
        num=num%50;
        for(;i<len;i++){
            s+='L';
        }

        len=len+2*(num/40);
        num=num%40;
        for(;i<len;i=i+2){
            s+='X';
            s+='L';
        }

        len=len+num/10;
        num=num%10;
        for(;i<len;i++){
            s+='X';
        }

        len=len+2*(num/9);
        num=num%9;
        for(;i<len;i=i+2){
            s+='I';
            s+='X';
        }

        len=len+(num/5);
        num=num%5;
        for(;i<len;i++){
            s+='V';
        }

        len=len+2*(num/4);
        num=num%4;
        for(;i<len;i=i+2){
            s+='I';
            s+='V';
        }

        len=len+num;
        for(;i<len;i++){
            s+='I';
        }

        return s;
    }
};

當然還是推薦使用字典或者某種表的方式

class Solution {
public:
    string intToRoman(int num) {
        int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        string reps[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

        string res;
        int 
        for (int i = 0; i < 13; i ++ )  //這裡不使用圖裡的count了,一遍一遍來就行了
            while(num >= values[i])
            {
                num -= values[i];
                res += reps[i];
            }
        return res;
    }
};

相關文章