林被 a Coder

每天进步一点

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

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())
}


阅读更多
个人分类: kotlin
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭