leetcode 12. integer to roman 算法

Given an integer, convert it to a roman numeral.

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

算法

常量数组转化表进行匹配

int Num[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
string Roman[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

C++代码

class Solution {
public:
    /*
    题意:将数字转换成罗马数字
    对照转换表模拟即可
    */
    string intToRoman(int num) {
        int Num[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        string Roman[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        string ans = "";
        int i = 0, times;
        while (num) {
            times = num / Num[i];
            num %= Num[i];
            while (times--) ans += Roman[i];
            i++;
        }
        return ans;
    }
};

Bug Free Procedure 从记事本直接写代码

2016.12.06 变量未定义
1. 用于指示转换数组位置的变量$i$没有定义