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/

  • 相关阅读:
    学习进度03
    构建之法阅读笔记03
    软件工程结队作业01
    用图像算法增强夜视效果
    python将指定目录下的所有文件夹用随机数重命名
    python脚本中调用其他脚本
    opencv+python实现图像锐化
    机器学习中减弱不同图像数据色调及颜色深浅差异
    python利用列表文件遍历
    python文件处理-检查文件名/路径是否正确
  • 原文地址:https://www.cnblogs.com/graph/p/3209402.html
Copyright © 2011-2022 走看看