<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script type="text/javascript" src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
输入罗马数字:<input type="text" v-model="roma"/> <button @click="change">转换</button>
<div>
阿拉伯数字: {{alb}}
</div>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
roma: '',
alb: ''
},
methods: {
change: function(){
var romaToAlb = new RomaToAlb();
var oString = this.roma
this.alb = romaToAlb.handle(oString, 0, oString.length)
}
},
})
// 规则:
// 罗马数字是阿拉伯数字传入之前使用的一种数码。罗马数字采用七个罗马字母作数字、即Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)。记数的方法:
// 相同的数字连写,所表示的数等于这些数字相加得到的数,如 III=3;
// 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 VIII=8、XII=12;
// 小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9;
/****
创建构造函数
*****/
function RomaToAlb (){
this.roma = ['I','V','X','L','C','D','M'];
this.alb = [1,5,10,50,100,500,1000];
/**
// 查找对应值
// v: String 罗马数字元素
// return Number 对应阿拉伯数字
// **/
RomaToAlb.prototype.single = function(v){
for(let i = 0; i < 7; i++){
if(this.roma[i] === v){
return this.alb[i]
}
}
}
/**
查找最大值下标
s: Array 需要转换的数组
l: Number 默认最大值索引
r: Number 字符串长度
return maxIndex: Number 最大值索引
**/
RomaToAlb.prototype.findMaxIndex = function(s, l, r){
let [max, maxIndex] = [this.single(s[l]), l]; //默认l为最大值的下标
for(let i = l + 1; i <= r; i++){
if(this.single(s[i]) > max){
max = this.single(s[i]);
maxIndex = i;
}
}
return maxIndex
}
/**
return Number 转换数字
**/
RomaToAlb.prototype.handle = function(s, l, r){
var maxIndex = 0;
if(l == r){
return this.single(s[l]) || 0
}
if(l > r){
return 0
}else{
maxIndex = this.findMaxIndex(s, l, r);
return this.single(s[maxIndex]) + this.handle(s, maxIndex + 1, r) - this.handle(s, l, maxIndex - 1);
}
}
}
</script>
</body>
</html>