-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.js
More file actions
68 lines (46 loc) · 1.18 KB
/
Copy pathstack.js
File metadata and controls
68 lines (46 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
var Stack = function () {
var items = [];
this.push = function (element) {
items.push(element);
};
this.pop = function () {
return items.pop();
};
this.peek = function () {
return items[items.length - 1];
};
this.isEmpty = function () {
return items.length === 0;
};
this.clear = function () {
items = [];
};
this.size = function () {
return items.length;
};
this.print = function () {
console.log(items.toString());
};
};
// 用栈数据结构完成一个进制转换方法
var baseConverter = function (decNumber, base) {
var resultArray = new Stack(),
digits = '0123456789ABCDEF',
tempNumber,
result;
while (decNumber > 0) {
tempNumber = Math.floor(decNumber % base);
resultArray.push(tempNumber);
decNumber = Math.floor(decNumber / base);
}
while (!resultArray.isEmpty()) {
result += digits[resultArray.pop()];
}
return result;
};
// 测试用例
baseConverter(3, 2); // 11
baseConverter(11, 8); // 13
baseConverter(11, 10); // 11
baseConverter(20, 16); // 14
baseConverter(12, 16); // C