Skip to content

Commit c40a443

Browse files
Excel sheet column
Signed-off-by: Leo Ma <begeekmyfriend@gmail.com>
1 parent b1e31af commit c40a443

File tree

4 files changed

+64
-0
lines changed

4 files changed

+64
-0
lines changed

168_excel_sheet_column_title/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test sheet_column.c
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
static char *convertToTitle(int n)
5+
{
6+
if (n <= 0) {
7+
return "";
8+
}
9+
10+
char *result = malloc(1024);
11+
int len = 0;
12+
do {
13+
result[len++] = ((n - 1) % 26) + 'A';
14+
n = (n - 1) / 26;
15+
} while (n > 0);
16+
result[len] = '\0';
17+
18+
int i, j;
19+
for (i = 0, j = len - 1; i < j; i++, j--) {
20+
char c = result[i];
21+
result[i] = result[j];
22+
result[j] = c;
23+
}
24+
return result;
25+
}
26+
27+
int main(int argc, char **argv)
28+
{
29+
if (argc != 2) {
30+
fprintf(stderr, "Usage: ./test n\n");
31+
exit(-1);
32+
}
33+
34+
printf("%s\n", convertToTitle(atoi(argv[1])));
35+
return 0;
36+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test sheet_column.c
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
static int titleToNumber(char *s)
5+
{
6+
int n = 0;
7+
while (*s != '\0') {
8+
n *= 26;
9+
n += *s++ - 'A' + 1;
10+
}
11+
12+
return n;
13+
}
14+
15+
int main(int argc, char **argv)
16+
{
17+
if (argc != 2) {
18+
fprintf(stderr, "Usage: ./test ABC\n");
19+
exit(-1);
20+
}
21+
22+
printf("%d\n", titleToNumber(argv[1]));
23+
return 0;
24+
}

0 commit comments

Comments
 (0)