zoukankan      html  css  js  c++  java
  • 12. Integer to Roman

    description:

    把阿拉伯数字转换成罗马数字

    Note:

    Example 1:
    
    Input: 3
    Output: "III"
    Example 2:
    
    Input: 4
    Output: "IV"
    Example 3:
    
    Input: 9
    Output: "IX"
    Example 4:
    
    Input: 58
    Output: "LVIII"
    Explanation: L = 50, V = 5, III = 3.
    Example 5:
    
    Input: 1994
    Output: "MCMXCIV"
    Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
    

    my answer:

    感恩

    大佬的answer:真的在leetcode里写代码的时候要时刻注意还是不是英文半角,要不然真的崩溃,哪出错都不知道

    class Solution {
    public:
        string intToRoman(int num) {
            string res = "";
            vector<int> value = {1000, 500, 100, 50, 10, 5, 1};
            vector<char> roman = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
            for(int n = 0; n < 7; n += 2){
                int x = num / value[n];
                if (x < 4){
                    for (int i = 1; i <= x; i++) res += roman[n];
                }
                else if(x == 4){
                    res = res + roman[n] + roman[n - 1];
                }
                else if(x > 4 && x < 9){
                    res += roman[n - 1];
                    for (int i = 6; i <= x; i++) res += roman[n];
                
                }else if(x == 9){
                    res = res + roman[n] + roman[n -2];
                } 
                num %= value[n];
            }
            return res;
        }
    };
    

    relative point get√:

    hint :

    在4和9处讨论好分割点,其实比较easy辣,思路逻辑神马的都还ok。

  • 相关阅读:
    第五周学习进度条
    课堂实验4.1(环数组)
    每日站立会议(3)
    每日站立会议(2)
    找水王
    购买一批书的最低价格
    每日站立会议(1)
    NABCD分析
    团队开发博客
    返回一个二维整数数组中的最大子数组之和(环)
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10619050.html
Copyright © 2011-2022 走看看