LeetCode - Integer to Roman

本文介绍了一种将整数转换为罗马数字的算法实现,适用于1到3999范围内的整数。通过分析罗马数字的构成规律,采用循环遍历的方法逐位构建对应的罗马数字字符串。

Given an integer, convert it to a roman numeral.

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

http://oj.leetcode.com/problems/integer-to-roman/


Solution:

First let's review the roman number: I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000

Basically it is to start from the MSB to LSB. There are 6 kinds of roman numbers and we use a for loop to scan it.

If the digit is less or equal to 3, it should be I~III, X~XXX, C~CCC or M~MMM.

If the digit is 4, it should be IV, XL or CD.

If the digit is 5, it should be V, L or D.

If the digit is from 6 to 8, it should be VI~VIII, LX~LXXX or DC~DCCC.

If the digit is 9, it should be like XI, CX or MC.

Since we check the int like 1000, 100, 10 and 1. So everytime we move 2 elements in the for loop.

https://github.com/starcroce/leetcode/blob/master/int_to_roman.cpp

// 360 ms for 3999 test cases
class Solution {
public:
    string intToRoman(int num) {
        char symbol[7] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
        string res;
        int scale = 1000;
        // for loop to scan symbol[]
        for(int i = 6; i >= 0; i -= 2) {
            int digit = num / scale;
            if(digit != 0) {
                // append sth like I to III
                if(digit <= 3) {
                    res.append(digit, symbol[i]);
                }
                // append sth like IV
                if(digit == 4) {
                    res.append(1, symbol[i]);
                    res.append(1, symbol[i+1]);
                }
                // append sth like V
                if(digit == 5) {
                    res.append(1, symbol[i+1]);
                }
                // append sth like VI to VIII
                if(digit > 5 && digit <= 8) {
                    res.append(1, symbol[i+1]);
                    res.append(digit-5, symbol[i]);
                }
                // append sth like IX
                if(digit == 9) {
                    res.append(1, symbol[i]);
                    res.append(1, symbol[i+2]);
                }
            }
            num = num % scale;
            scale /= 10;
        }
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值