83 lines
1.6 KiB
C
83 lines
1.6 KiB
C
#include<string.h>
|
|
#include<stdio.h>
|
|
|
|
|
|
int titleToNumber(char* columnTitle) {
|
|
int len = strlen(columnTitle);
|
|
|
|
int factor = 1;
|
|
int num = 0;
|
|
|
|
// Loop from the beginning
|
|
int i = len-1;
|
|
while (1) {
|
|
// Get char
|
|
char c = columnTitle[i];
|
|
|
|
// Convert char to int by using ASCII table and subtracting A=65
|
|
// so 64
|
|
int cNum = c - 64;
|
|
|
|
// Add sum
|
|
num += cNum*factor;
|
|
|
|
// Perform check before increasing factor
|
|
i--;
|
|
if (i < 0) break;
|
|
factor *= 26;
|
|
}
|
|
|
|
return num;
|
|
}
|
|
|
|
// Has a max length of "FXSHRXW," so allocate buffer of 8.
|
|
char out[8] = {0};
|
|
|
|
// Performs a counter with letters.
|
|
void doInc(char* str) {
|
|
(*str)++;
|
|
if (*str == '[') {
|
|
*str = 'A';
|
|
return doInc(str - sizeof(char));
|
|
}
|
|
}
|
|
|
|
char* convertToTitle(int number) {
|
|
|
|
char* str = &out[6];
|
|
// Fill array with default values
|
|
strcpy(out, "@@@@@@@");
|
|
while(number > 0) {
|
|
// Increment first
|
|
doInc(str);
|
|
number--;
|
|
}
|
|
|
|
str = out;
|
|
while(*str == '@') str++;
|
|
|
|
// Return pointer to array starting from first character, 7-i.
|
|
return str;
|
|
}
|
|
|
|
|
|
int main() {
|
|
printf("%d\n", titleToNumber("A"));
|
|
printf("%d\n", titleToNumber("B"));
|
|
printf("%d\n", titleToNumber("C"));
|
|
printf("%d\n", titleToNumber("Z"));
|
|
printf("%d\n", titleToNumber("AA"));
|
|
printf("%d\n", titleToNumber("AB"));
|
|
printf("%d\n", titleToNumber("ZZ"));
|
|
|
|
printf("%s\n", convertToTitle(1));
|
|
printf("%s\n", convertToTitle(2));
|
|
printf("%s\n", convertToTitle(3));
|
|
printf("%s\n", convertToTitle(26));
|
|
printf("%s\n", convertToTitle(27));
|
|
printf("%s\n", convertToTitle(28));
|
|
printf("%s\n", convertToTitle(701));
|
|
printf("%s\n", convertToTitle(2147483647));
|
|
return 0;
|
|
}
|