Skip to content

Commit f71a0a5

Browse files
committed
Solve problem '168) excel sheet column title'
1 parent 97b8719 commit f71a0a5

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_.
2+
3+
For example:
4+
5+
```
6+
A -> 1
7+
B -> 2
8+
C -> 3
9+
...
10+
Z -> 26
11+
AA -> 27
12+
AB -> 28
13+
...
14+
```
15+
16+
**Example 1:**
17+
18+
```
19+
Input: columnNumber = 1
20+
Output: "A"
21+
```
22+
23+
**Example 2:**
24+
25+
```
26+
Input: columnNumber = 28
27+
Output: "AB"
28+
```
29+
30+
**Example 3:**
31+
32+
```
33+
Input: columnNumber = 701
34+
Output: "ZY"
35+
```
36+
37+
**Constraints:**
38+
39+
- `1 <= columnNumber <= 2^31 - 1`
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
func main() {
8+
fmt.Println(convertToTitle(1))
9+
fmt.Println(convertToTitle(28))
10+
fmt.Println(convertToTitle(701))
11+
}
12+
13+
func convertToTitle(columnNumber int) string {
14+
result := []byte{}
15+
for columnNumber > 0 {
16+
result = append(result, 'A'+byte((columnNumber-1)%26))
17+
columnNumber = (columnNumber - 1) / 26
18+
}
19+
for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
20+
result[i], result[j] = result[j], result[i]
21+
}
22+
23+
return string(result)
24+
}

0 commit comments

Comments
 (0)