关闭

kotlin实现罗马数字和阿拉伯数字转换

370人阅读 评论(0) 收藏 举报
分类:

1.罗马数字转阿拉伯数字

遍历罗马数字的每一位,若当前位比前一位小,则在结果中加上当前位

否则在结果中减去前一位的两倍再加上当前位


2.阿拉伯数字转罗马数字

先构造map

mapOf(1000 to "M",900 to "CM",500 to "D",400 to "CD",100 to "C",90 to "XC",50 to "L",40 to "XL",10 to "X",9 to "IX",5 to "V",4 to "IV",1 to "I")
遍历map

若当前数字大于第i个数字

将第i个数字对应的字母加入结果中,当前数字-=第i个数字

val romeChar=mapOf(
        'I' to 1,
        'V' to 5,
        'X' to 10,
        'L' to 50,
        'C' to 100,
        'D' to 500,
        'M' to 1000
)


class RomeNumber private constructor(){
    constructor(number:String):this(){
        this.number=number
    }
    var number:String=""
        set(value){
            if(value.toCharList().any{!romeChar.containsKey(it)}) throw object :Exception("It is not a legal Rome Number"){ } else $number=value.toUpperCase()
        }
    public fun toArabicNumber():Int{
        var lastNumber=0
        var sum=0
        number.toCharList().forEach {
            var value:Int?=romeChar.get(it)
            if (value!!>lastNumber) {sum-=lastNumber*2;sum+=value;}else sum+=value
            lastNumber=value
        }
        return sum
    }

    override fun toString(): String {
        return number
    }
}


fun Int.toRomeNumber():RomeNumber{
    val additionMap = mapOf(1000 to "M",900 to "CM",500 to "D",400 to "CD",100 to "C",90 to "XC",50 to "L",40 to "XL",10 to "X",9 to "IX",5 to "V",4 to "IV",1 to "I")
    val sb=StringBuilder()
    var temp=this
    while (temp != 0) {
        additionMap.forEach {
            while (temp >= it.getKey()) {
                sb.append(it.getValue())
                temp -= it.getKey()
            }
        }
    }
    return RomeNumber(sb.toString())
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:20982次
    • 积分:359
    • 等级:
    • 排名:千里之外
    • 原创:16篇
    • 转载:0篇
    • 译文:0篇
    • 评论:3条
    文章分类
    最新评论