Skip to content

Commit c2f13c8

Browse files
Excel Sheet Column Title : Accepted
1 parent bea89e5 commit c2f13c8

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ My accepted leetcode solutions to some of the common interview problems.
145145
- [Rotate Function](problems/src/math/RotateFunction.java) (Medium)
146146
- [Water and Jug Problem](problems/src/math/WaterAndJugProblem.java) (Medium)
147147
- [Add Digits](problems/src/math/AddDigits.java) (Easy)
148+
- [Excel Sheet Column Title](problems/src/math/ExcelSheetColumnTitle.java) (Easy)
148149

149150
#### [Stack](problems/src/stack)
150151

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package math;
2+
3+
/**
4+
* Created by gouthamvidyapradhan on 12/08/2017.
5+
* Given a positive integer, return its corresponding column title as appear in an Excel sheet.
6+
7+
For example:
8+
9+
1 -> A
10+
2 -> B
11+
3 -> C
12+
...
13+
26 -> Z
14+
27 -> AA
15+
28 -> AB
16+
*/
17+
public class ExcelSheetColumnTitle {
18+
19+
private static final String CONST = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
20+
/**
21+
* Main method
22+
* @param args
23+
* @throws Exception
24+
*/
25+
public static void main(String[] args) throws Exception{
26+
System.out.println(new ExcelSheetColumnTitle().convertToTitle(52));
27+
}
28+
29+
30+
public String convertToTitle(int n) {
31+
StringBuilder ans = new StringBuilder();
32+
while(n > 0){
33+
int mod = n % 26;
34+
n /= 26;
35+
if(mod == 0){
36+
ans.append('Z');
37+
n -= 1;
38+
}else{
39+
ans.append(CONST.charAt(mod - 1));
40+
}
41+
}
42+
return ans.reverse().toString();
43+
}
44+
45+
}

0 commit comments

Comments
 (0)