Skip to content

Commit b63cb04

Browse files
committed
罗马字符串转化成整数
1 parent 981a7fa commit b63cb04

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

algorithms/mergeTwoLists/mergeTwoLists.js

+13-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,15 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} list1
10+
* @param {ListNode} list2
11+
* @return {ListNode}
12+
*/
113
var mergeTwoLists = function(list1, list2) {
214
// 数组的解法
315
// let targetList = list1;
@@ -9,6 +21,7 @@ var mergeTwoLists = function(list1, list2) {
921
// return targetList;
1022

1123
// 链表
24+
// 每次传进来的是 ListNode
1225
if (list1 === null) return list2;
1326
if (list2 === null) return list1;
1427

@@ -20,5 +33,3 @@ var mergeTwoLists = function(list1, list2) {
2033
return list2
2134
}
2235
};
23-
24-
console.log(mergeTwoLists([1, 2, 3], [2, 3, 8]));

algorithms/romanToInt/romanToInt.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
var romanToInt = function(s) {
6+
const map = {
7+
I: 1,
8+
V: 5,
9+
IX: 9,
10+
X: 10,
11+
XL: 40,
12+
L: 50,
13+
XC: 90,
14+
C: 100,
15+
CD: 400,
16+
D: 500,
17+
CM: 900,
18+
M: 1000
19+
};
20+
let result = 0;
21+
for (let i = 0; i < s.length;) {
22+
// 两种情况,一位或者两位
23+
if (i + 1 < s.length && map[s.substring(i, i+2)]) {
24+
result += map[s.substring(i, i+2)];
25+
i += 2;
26+
} else {
27+
result += map[s.substring(i, i+1)];
28+
i++;
29+
}
30+
}
31+
32+
console.log(result);
33+
return result;
34+
};

0 commit comments

Comments
 (0)