LeetCode 12 Integer to Roman

标签: 模拟题 LeetCode 发布于:2022-03-21 12:44:57 编辑于:2022-03-21 12:44:57 浏览量:724

概述

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

解法

写的时候注意 while 里面那些判断是 >=

class Solution {
public:
    string intToRoman(int num) {
        string ans;
        int numM = num / 1000;
        ans += string(numM, 'M');
        num -= numM * 1000;
        vector<string> cfgs = {"IVX", "XLC", "CDM"};
        int i = int(to_string(num).size()) - 1;
        while (i != -1) {
            int base = pow(10, i);
            // < 1000
            if (num >= 9 * base) {
                num -= 9 * base;
                ans += cfgs[i][0];
                ans += cfgs[i][2];
            }
            // < 900
            if (num >= 5 * base) {
                num -= 5 * base;
                ans += cfgs[i][1];
            }
            // < 500
            if (num >= 4 * base) {
                num -= 4 * base;
                ans += cfgs[i][0];
                ans += cfgs[i][1];
            }
            // make it < 100
            int numM = num / base;
            num -= numM * base;
            ans += string(numM, cfgs[i][0]);
            i --;
        }
        return ans;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/