[Leetcode] 12 - Integer to Roman

本文介绍了一种将整数转换为罗马数字的算法实现。通过维护特定的字符映射和迭代处理每一位数字,该算法能高效地完成转换任务。

原题链接:https://oj.leetcode.com/problems/integer-to-roman/


这题也是简单题,重点是要维持一个罗马数字的数组,然后每位计算时候,则数组往后扫2位,使用同样的计算方式得出当前位的罗马表示。


class Solution {
public:
    string intToRoman(int num) {
        char map[7] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
        
        string res = "";
        int shift = 0;
        while (num) {
            int cur = num % 10;
            res = getStr(map + shift, cur) + res;
            num /= 10;
            shift += 2;
        }
        
        return res;
    }
    
    string getStr(char map[], int num) {
        string res = "";
        if (num > 0 && num < 4) {
            res.append(num, map[0]);
        } else if (num == 4) {
            res.append(1, map[0]);
            res.append(1, map[1]);
        } else if (num == 5) {
            res.append(1, map[1]);
        } else if (num > 5 && num < 9) {
            res.append(1, map[1]);
            res.append(num - 5, map[0]);
        } else if (num == 9) {
            res.append(1, map[0]);
            res.append(1, map[2]);
        }
        
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值