forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExcelSheetColumnTitle.java
47 lines (41 loc) · 1008 Bytes
/
ExcelSheetColumnTitle.java
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
package math;
/**
* Created by gouthamvidyapradhan on 12/08/2017.
* Given a positive integer, return its corresponding column title as appear in an Excel sheet.
* <p>
* For example:
* <p>
* 1 -> A
* 2 -> B
* 3 -> C
* ...
* 26 -> Z
* 27 -> AA
* 28 -> AB
*/
public class ExcelSheetColumnTitle {
private static final String CONST = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* Main method
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
System.out.println(new ExcelSheetColumnTitle().convertToTitle(52));
}
public String convertToTitle(int n) {
StringBuilder ans = new StringBuilder();
while (n > 0) {
int mod = n % 26;
n /= 26;
if (mod == 0) {
ans.append('Z');
n -= 1;
} else {
ans.append(CONST.charAt(mod - 1));
}
}
return ans.reverse().toString();
}
}