diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /excel_sheet_column_title.c | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'excel_sheet_column_title.c')
-rw-r--r-- | excel_sheet_column_title.c | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/excel_sheet_column_title.c b/excel_sheet_column_title.c new file mode 100644 index 0000000..14c55be --- /dev/null +++ b/excel_sheet_column_title.c @@ -0,0 +1,49 @@ +// 168. Excel Sheet Column Title +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +/* + * given an integer 'column_number', return its corresponding column title as it + * appears in an excel sheet. for example: A -> 1 B -> 2 C -> 3 + * ... + * Z -> 26 + * AA -> 27 + * AB -> 28 + * ... + */ + +int get_len(int n) { + int i = 0; + while (n) { + if (!(n % 26)) + n = (n - 1) / 26; + else + n /= 26; + i++; + } + return i; +} + +char *convertToTitle(int n) { + int len = get_len(n); + char *ans = (char *)malloc(sizeof(*ans) * (len + 1)); + memset(ans, 0, len + 1); + while (n) { + --len; + if (!(n % 26)) { + ans[len] = 'Z'; + n = (n - 1) / 26; + } else { + ans[len] = 'A' + (n % 26) - 1; + n /= 26; + } + } + return ans; +} + +int main() { + printf("%s\n", convertToTitle(1)); // expect: A + printf("%s\n", convertToTitle(28)); // expect: AB + printf("%s\n", convertToTitle(701)); // expect: ZY +} |