美文网首页
Integer to Roman go语言实现

Integer to Roman go语言实现

作者: fjxCode | 来源:发表于2018-09-22 15:36 被阅读0次

    Integer to Roman

    题目描述

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

    思路:

    • 按面值求余。

    解:

    package main
    
    import "fmt"
    
    func intToRoman(num int) string {
        //M CM D CD C XC L XL X IX V IV I
        //1000 900 500 400 100 90 50 40 10 9 5 4 1
    
        res := ""
        for ; num >= 1000;  {
            num -= 1000
            res += "M"
        }
        for ; num >= 900;  {
            num -= 900
            res += "CM"
        }
        for ; num >= 500;  {
            num -= 500
            res += "D"
        }
        for ; num >= 400;  {
            num -= 400
            res += "CD"
        }
        for ; num >= 100;  {
            num -= 100
            res += "C"
        }
        for ; num >= 90;  {
            num -= 90
            res += "XC"
        }
        for ; num >= 50;  {
            num -= 50
            res += "L"
        }
        for ; num >= 40;  {
            num -= 40
            res += "XL"
        }
        for ; num >= 10;  {
            num -= 10
            res += "X"
        }
        for ; num >= 9;  {
            num -= 9
            res += "IX"
        }
        for ; num >= 5;  {
            num -= 5
            res += "V"
        }
        for ; num >= 4;  {
            num -= 4
            res += "IV"
        }
        for ; num >= 1;  {
            num -= 1
            res += "I"
        }
        return res
    }
    func main()  {
        res := intToRoman(9)
        fmt.Print(res)
    }
    

    相关文章

      网友评论

          本文标题:Integer to Roman go语言实现

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