leetcode 12

来源:互联网 发布:淘宝卖家中心手机版 编辑:程序博客网 时间:2024/04/28 01:57

Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.

// 1~9: {“I”, “II”, “III”, “IV”, “V”, “VI”, “VII”, “VIII”, “IX”};
// 10~90: {“X”, “XX”, “XXX”, “XL”, “L”, “LX”, “LXX”, “LXXX”, “XC”};
// 100~900: {“C”, “CC”, “CCC”, “CD”, “D”, “DC”, “DCC”, “DCCC”, “CM”};
// 1000~3000: {“M”, “MM”, “MMM”}.

class Solution {public:    string intToRoman(int num) {        string roman = "IVXLCDM";        string ret;        string::const_iterator it = roman.begin();        while (num) {            int tmp = num % 10;            if (tmp <= 3) ret = string(tmp, *it) + ret;            else if (tmp == 4) ret = string(1, *(it)) + *(it + 1) + ret;            else if (tmp < 9) ret = string(1, *(it + 1)) + string(tmp - 5, *it) + ret;            else ret = string(1, *(it)) + *(it + 2) + ret;            num /= 10;            it +=2;        }        return ret;           }};
原创粉丝点击