-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexcel-sheet-column-title.js
46 lines (44 loc) · 1.02 KB
/
excel-sheet-column-title.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
/**
* Source: https://leetcode.com/problems/excel-sheet-column-title/
* Tags: [Math]
* Level: Easy
* Updated: 2015-04-24
* Title: Excel Sheet Column Title
* Auther: @imcoddy
* Content: 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
*
* Credits:Special thanks to @ifanchu for adding this problem and creating all test cases.
*/
/**
* @param {number} n
* @return {string}
*/
var convertToTitle = function(n) {
var str = 'ZABCDEFGHIJKLMNOPQRSTUVWXYZ';
var size = 26;
var result = '';
while( n > 0 ){
result = str.charAt(n % size) + result ;
if (n % size === 0) {
n = n - size;
}
n = Math.floor( n / size );
}
console.log(result);
return result;
};
convertToTitle(25); // X
convertToTitle(26); // Z
convertToTitle(27); // AA
convertToTitle(52); // AA
convertToTitle(26*26); // AA