leetcode - Integer to Roman

来源:互联网 发布:小米任我行联通4g知乎 编辑:程序博客网 时间:2024/06/04 23:20

Given an integer, convert it to a roman numeral.

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

//因为题目的要求是1-3999,所以,将罗马符号与其对应的数字直接搞成表,//便于查找。剩下的就是利用减法来依次从大到小减去相应的数字,//假设,给出数字是num,那么,只要将num每次从ans数字,从大到小减去相应的数字(对应罗马符号)。class Solution {public:    std::string intToRoman(int num) {int ans[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };std::string res[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };std::string s;for (int i = 0; i < sizeof(ans)/4; i++){while(num >= ans[i]){num -= ans[i];s.append(res[i]);}}#if 1std::cout << s << std::endl;#endif // 1return s;    }};

0 0