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

370人阅读 评论(0)

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

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

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 romeChar=mapOf(
'I' to 1,
'V' to 5,
'X' to 10,
'L' to 50,
'C' to 100,
'D' to 500,
'M' to 1000
)

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

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) {
while (temp >= it.getKey()) {
sb.append(it.getValue())
temp -= it.getKey()
}
}
}
}

0
0

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