Skip to content

Commit 4601cbb

Browse files
committed
feat(aligorithms): redix
1 parent 5f91eb9 commit 4601cbb

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/algorithms/radix/index.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
* @Author: Rainy [https://github.com/rain120]
3+
* @Date: 2022-01-24 12:12:01
4+
* @LastEditors: Rainy
5+
* @LastEditTime: 2022-01-24 12:18:06
6+
*/
7+
8+
const getNRadix = (n: number) => {
9+
const radixList = [];
10+
11+
for (let i = 0; i < n; i++) {
12+
if (i < 10) {
13+
radixList.push(i);
14+
} else {
15+
// A 65 Z 90, a 97 z 122
16+
// i = 10+ => i + (65 - 10)
17+
// i = 36+ => i + 62
18+
const A = 65;
19+
const Z = 90;
20+
const a = 97
21+
const code = i + (A - 10) < Z ? (i + (A - 10)) : i + (a - (Z - 55));
22+
radixList.push(String.fromCharCode(code));
23+
}
24+
}
25+
26+
return radixList;
27+
}
28+
29+
function getRadixValue(value: number, radix = 10) {
30+
if (radix < 1) {
31+
throw new TypeError(`Invalid with ${radix}`);
32+
}
33+
34+
const res = [];
35+
const radixList = getNRadix(radix);
36+
37+
while(value) {
38+
const v = value % radix;
39+
40+
res.unshift(radixList[v]);
41+
42+
// @ts-ignore
43+
value = parseInt(value / radix);
44+
}
45+
46+
return res.join('');
47+
}

0 commit comments

Comments
 (0)