Toggle navigation
Toggle navigation
This project
Loading...
Sign in
Shenlin
/
leetcode-test
Go to a project
Toggle navigation
Toggle navigation pinning
Projects
Groups
Snippets
Help
Project
Activity
Repository
Pipelines
Graphs
Issues
0
Merge Requests
0
Wiki
Snippets
Network
Create a new issue
Builds
Commits
Issue Boards
Authored by
lintry
2025-02-24 16:41:23 +0800
Browse Files
Options
Browse Files
Download
Email Patches
Plain Diff
Commit
638e271afaed7d09d04e508dc22764413faba382
638e271a
1 parent
5d962546
add #13
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
84 additions
and
0 deletions
13-romanToInt.js
13-romanToInt.js
0 → 100644
View file @
638e271
/**
* @param {string} s
* @return {number}
*/
/*
var romanToInt = function (s) {
const dict = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
};
const sign = {
I: {V: -1, X:-1},
X: {L: -1, C: -1},
C: {D: -1, M: -1}
};
let num = 0;
let last;
s.split('').forEach(n => {
let c = dict[n];
if (!c) {
throw new Error('Wrong Roman Number');
}
})
};
//*/
// 定义罗马数字和对应的整数值映射表
const
romanToIntegerMap
=
new
Map
([
[
'I'
,
1
],
[
'V'
,
5
],
[
'X'
,
10
],
[
'L'
,
50
],
[
'C'
,
100
],
[
'D'
,
500
],
[
'M'
,
1000
]
]);
/**
* 将罗马数字转换为整数。
* @param {string} romanNumeral - 罗马数字字符串。
* @returns {number} 转换后的整数值。
*/
function
romanToInt
(
romanNumeral
)
{
const
regex
=
/^M
{0,4}(
CM|CD|D
?
C
{0,3})(
XC|XL|L
?
X
{0,3})(
IX|IV|V
?
I
{0,3})
$/
;
if
(
!
regex
.
test
(
romanNumeral
))
{
throw
new
Error
(
'Invalid Roman Numeral: '
+
romanNumeral
);
}
let
total
=
0
;
for
(
let
i
=
0
;
i
<
romanNumeral
.
length
;
i
++
)
{
const
currentChar
=
romanNumeral
[
i
];
const
currentValue
=
romanToIntegerMap
.
get
(
currentChar
);
if
(
!
currentValue
)
{
throw
new
Error
(
'Wrong Roman Number'
);
}
// 如果下一个字符的值大于当前字符,那么需要从总和中减去当前值
if
(
i
+
1
<
romanNumeral
.
length
&&
romanToIntegerMap
.
get
(
romanNumeral
[
i
+
1
])
>
currentValue
)
{
total
-=
currentValue
;
}
else
{
total
+=
currentValue
;
}
console
.
info
(
i
,
'-'
,
currentChar
,
':'
,
currentValue
,
'='
,
total
);
}
return
total
;
}
// 示例使用:
const
romanInput
=
'MCMXCIV'
;
console
.
info
(
`The integer value of
${
romanInput
}
is
${
romanToInt
(
romanInput
)}
.`
);
Please
register
or
login
to post a comment