DAY6:leetcode #12 Integer to Roman

来源:互联网 发布:最小凸包面积算法 编辑:程序博客网 时间:2024/05/16 00:59

Given an integer, convert it to a roman numeral.

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

很无聊的一道题。。。

我的代码很丑。。。

class Solution(object):    def intToRoman(self, num):        """        :type num: int        :rtype: str        """        rstr = ''        while num > 0:            if num >= 900 and num < 1000:                rstr += 'CM'                num -= 900                continue            elif num >= 90 and num < 100:                rstr += 'XC'                num -= 90                continue            elif num == 9:                rstr += 'IX'                num -= 9                continue            elif num >= 400 and num < 500:                rstr += 'CD'                num -= 400                continue            elif num >= 40 and num < 50:                rstr += 'XL'                num -= 40                continue            elif num == 4:                rstr += 'IV'                num -= 4                continue            elif num >= 1000:                rstr += 'M'                num -= 1000                continue            elif num >= 500:                rstr += 'D'                num -= 500                continue            elif num >= 100:                rstr += 'C'                num -= 100                continue            elif num >= 50:                rstr += 'L'                num -= 50                continue            elif num >= 10:                rstr += 'X'                num -= 10                continue            elif num >= 5:                rstr += 'V'                num -= 5                continue            elif num >= 0:                rstr += 'I'                num -= 1                continue        return rstr

看一个能让代码简洁的例子:


class Solution 2 { 3 public: 4     string intToRoman(int num) 5     { 6         int n[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 7         string r[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 8          9         string s = "";10         for(int i = 0; num > 0; num %= n[i], ++ i)11             for(int j = 0, k = num / n[i]; j < k; ++ j)12                 s += r[i];13         return s;14     }15 };
主要是用两个数组把那些复杂的if判断省略掉了。

0 0
原创粉丝点击