-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
function romanToInt(s) { | ||
const roman = { | ||
I: 1, | ||
V: 5, | ||
X: 10, | ||
L: 50, | ||
C: 100, | ||
D: 500, | ||
M: 1000 | ||
} | ||
const N = s.length - 1 | ||
let result = roman[s[N]] | ||
|
||
for (let i = 0, c, n; i < N; i++) { | ||
c = roman[s[i]] | ||
n = roman[s[i + 1]] | ||
result += c < n ? -c : c | ||
} | ||
|
||
return result | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
### 代码实现 | ||
[013.RomanToInteger](013.RomanToInteger.js) | ||
|
||
### 解题思路 | ||
罗马数字有一个特征:两个相邻的字符,如果左边比右边大,那么两个数应该相加,如果左边比右边小,那么这两个数应该相减。根据这个特点,可以写出下面的计算过程: | ||
```js | ||
for (let i = 0, c, n; i < N; i++) { | ||
c = roman[s[i]] | ||
n = roman[s[i + 1]] | ||
result += c < n ? -c : c | ||
} | ||
``` | ||
依次将结果加上或减去罗马数的值,就将整个罗马数转换为了数字。 |