LeetCode | Integer to Roman

题目:

Given an integer, convert it to a roman numeral.

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

思路:

基本思路是将整数按照10进制存到一个数组中,针对每个数根据>5,=5,<5做处理。

代码:

class Solution {
public:
    string intToRoman(int num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function    
        char number[8] = {' ','I','V','X','L','C','D','M'};
        
        int data[5];
        int len = 0;
        
        string result;
        
        while(num != 0)
        {
            data[len++] = num%10;
            num /= 10;
        };
        
        for(int i = len - 1; i >=0; i--)
        {
            int skip = data[i]/5;
            int cur = data[i]%5;
            
            if(data[i] == 5)
            {
                if(skip > 0)
                {
                    result.push_back(number[2*(i+1)]);
                }
            }
            else if(cur <= 3)
            {
                if(skip>0)
                {
                    result.push_back(number[2*(i+1)]);
                }
                for(int j = 0; j < cur;j++)
                {
                    result.push_back(number[2*i+1]);
                }
            }
            else if(cur == 4)
            {
                result.push_back(number[2*i+1]);
                result.push_back(number[2*(i+1) + skip]);
            }
            
        }
        return result;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11703321
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞