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倍。
    个位应该是:I,II,III,IV,V,VI,VII,VIII,IX
    十位应该是:X,XX,XXX,XL,L,LX,LXX,LXXX,XC
    百位应该是:C,CC,CCC,CD,D,DC,DCC,DCCC,CM

    千位就是:  M,MM,MMM

    从高位到地位取值,然后把字符串拼凑起来即可。

    string romans[4][10] =
    {
        {"","I", "II","III","IV","V","VI","VII","VIII","IX" },
        {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
        {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
        {"","M","MM","MMM"}
    };
    
    class Solution {
        public:
            string digitToRoman(int digit, int pow)
            {
                return romans[pow][digit];
            }   
    
            string intToRoman(int num)
            {
                int base = 1000;
                int digit = 0;
                int pow = 4 - 1;
                string result;
    
                while(num)
                {
                    digit = num/base;
                    result += digitToRoman(digit, pow);
                    num = num%base;
                    base /= 10;
                    pow --;
                }
                return result;
    
            }
    };
  • 相关阅读:
    作用域链及作用域面试题
    this在js中的作用
    dom对象
    作用域问题
    逻辑运算
    socket.io 的使用
    mongoDB 的使用
    使用 usb 调试的时候,连接上电脑没反应
    uni-app 的更新及碰到的问题
    WebSocket 的使用
  • 原文地址:https://www.cnblogs.com/diegodu/p/4275304.html
Copyright © 2011-2022 走看看