美文网首页
Integer to Roman

Integer to Roman

作者: Jun_简书 | 来源:发表于2019-05-09 12:45 被阅读0次

    [原题链接-M] (https://leetcode.com/problems/integer-to-roman/description/)

    Example
    罗马数字问题

    时间复杂度: O(N)- 空间复杂度: O(1)

    这个题关键点在于穷举
    
    print_r(test(1994));
    
    function test($num) {
        $lookup = [
                'M' => 1000, 
                'CM'=> 900, 
                'D'=> 500, 
                'CD'=> 400, 
                'C'=> 100, 
                'XC'=> 90, 
                'L'=> 50, 
                'XL'=> 40, 
                'X'=> 10, 
                'IX'=> 9, 
                'V'=> 5, 
                'IV'=> 4, 
                'I'=> 1
            ];
            
        $roman = '';
        foreach ($lookup as $key => $value) {
            while ($num >= $value) {
                $roman .= $key;
                $num -= $value;
            }
        }
        
        return $roman;
    }    
    

    相关文章

      网友评论

          本文标题:Integer to Roman

          本文链接:https://www.haomeiwen.com/subject/ffhwoqtx.html