zoukankan      html  css  js  c++  java
  • 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.
    

      分析:

    罗马数字是由字符I,V,X,L,C,D,M等等表示的,其中
    I = 1;
    V = 5;
    X = 10;
    L = 50;
    C = 100;
    D = 500;
    M = 1000;
    接下来应该是V开始的重复,但是上面要加一个横线,表示对应数字的1000倍。
    而且对于某位上(以个位为例),19,应该是:I,II,III,IV,V,VI,VII,VIII,IX
    而,对于百位上,100900,应该是:C,CC,CCC,CD,D,DC,DCC,DCCC,CM
    依此类推。
    有一点比较有意思,那就是IV,正统的写法是IIII(写程序倒是容易些)。后来简写为IV,但是由于IV也是朱皮特神的名字,为了不让神的名字看起来像普通数字,这种简写遭到了很多人的抵制。
    class Solution {
    public:
        void appendNumtoRoman(int digit, string &roman, char *symbol)
        {
            if(digit == 0) return ;
            if(digit <= 3){
              roman.append(digit, symbol[0]);
            }else if( digit == 4){
              roman.append(1, symbol[0]);
              roman.append(1, symbol[1]);
            }else if(digit == 5){
              roman.append(1,symbol[1]);
            }else if(digit <= 8){
              roman.append(1, symbol[1]);
              roman.append(digit - 5, symbol[0]);
            }else if(digit == 9){
              roman.append(1, symbol[0]);
              roman.append(1, symbol[2]);
             }    
        }
        string intToRoman(int num) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function    
            char symbol[]={'I','V','X','L','C','D','M','v','x'};
            string roman = "";
            int scale = 1000;
            
            for(int i = 6; i >= 0; i -= 2)
            {
                int digit = num /scale ;
                appendNumtoRoman(digit, roman, symbol+i);
                num = num% scale;
                scale /= 10;
            }        
            
            return roman ;
        }
    };

    转自: http://blog.unieagle.net/2012/09/29/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Ainteger-to-roman/

  • 相关阅读:
    ajax处理响应(三)
    ajax起步 (二)
    ajax的使用(一)
    css相关用法
    vue 实例的生命周期
    vue中computed与watch的异同
    文本显示,单行超出和多行超出显示省略号
    vue+mui+html5+ plus开发的混合应用底部导航的显示与隐藏
    addEventListener()与removeEventListener(),追加事件和删除追加事件
    原生js中获取this与鼠标对象以及vue中默认的鼠标对象参数
  • 原文地址:https://www.cnblogs.com/graph/p/3209402.html
Copyright © 2011-2022 走看看