-
Notifications
You must be signed in to change notification settings - Fork 20
/
ExcelSheetColumnTitle.js
68 lines (58 loc) · 1.13 KB
/
ExcelSheetColumnTitle.js
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
/**
* Given a positive integer, return its corresponding column title as appear in an Excel sheet.
*
* For example:
*
* 1 -> A
* 2 -> B
* 3 -> C
* ...
* 26 -> Z
* 27 -> AA
* 28 -> AB
*
* Accepted.
*/
/**
* @param {number} n
* @return {string}
*/
let convertToTitle = function (n) {
let builder = "";
while (n !== 0) {
if (n % 26 === 0) {
builder = builder.concat("Z");
n -= 26;
} else {
builder = builder.concat(String.fromCharCode(n % 26 - 1 + 'A'.charCodeAt(0)));
n -= n % 26;
}
n = parseInt(n / 26);
}
return builder.split("").reverse().join("");
};
if (convertToTitle(1) === "A") {
console.log("pass")
} else {
console.error("failed")
}
if (convertToTitle(2) === "B") {
console.log("pass")
} else {
console.error("failed")
}
if (convertToTitle(26) === "Z") {
console.log("pass")
} else {
console.error("failed")
}
if (convertToTitle(27) === "AA") {
console.log("pass")
} else {
console.error("failed")
}
if (convertToTitle(28) === "AB") {
console.log("pass")
} else {
console.error("failed")
}