Excel Sheet Row Numbers | LeetCode
Given the sequence S1 = {a,b,c,d,…,x,y,z,aa,ab,ac…. } and given that this sequence corresponds (term for term) to the sequence S2 = {0,1,2,3,….}. Write code to convert an element of S2 to the corresponding element of S1.
You should be able to observe that from a-z (a total of 26), from aa-zz (a total of 262), from aaa-zzz (a total of263), and so on… I will explain why this is important later.
Given the sequence S1 = {a,b,c,d,…,x,y,z,aa,ab,ac…. } and given that this sequence corresponds (term for term) to the sequence S2 = {0,1,2,3,….}. Write code to convert an element of S2 to the corresponding element of S1.
You should be able to observe that from a-z (a total of 26), from aa-zz (a total of 262), from aaa-zzz (a total of263), and so on… I will explain why this is important later.
n = 26 + 262 + ... + 26k-1 + a0 + a1*26 + a2*262 + ... + ak-1*26k-1
= a0 + (a1 + 1) 26 + (a2 + 1) 262 + ... + (ak-1 + 1) 26k-1
where
ai ranges from 0-25 (each representing a letter in s1),
k is the number of letters in s1.
string numToStr(int n) {
string str(1, 'a' + n%26);
n = n/26;
while (n != 0) {
str = (char)('a' + (n-1)%26) + str;
n = (n-1)/26;
}
return str;
}
The advantage is the recursive solution can print the solution directly without storing the characters into a variable.
void numToStrHelper(int n) {
if (n == 0) return;
numToStrHelper((n-1)/26);
cout << (char)('a'+(n-1)%26);
}
void numTostr(int n) {
numToStrHelper(n/26);
cout << (char)('a'+n%26);
}
Read full article from Excel Sheet Row Numbers | LeetCode