Why using A = (A-1)/26 in interview bit solution?


#1

Why do we do A = (A-1)/26 instead of A=A/26 in solution from the interview bit?

string Solution::convertToTitle(int A) {
string ans;
while (A) {
ans = char ((A - 1) % 26 + ‘A’) + ans;
A = (A - 1) / 26;
}
return ans;
}


#2

It is because there’s a case where n = 26 or a multiple of 26, so n%26 will be equal to 0, this 0 should correspond to ‘Z’. So, in this solution, doing A - 1 ensures that 0 corresponds to ‘A’, 1 to ‘B’…, 25 to ‘Z’. This way we don’t have to worry about the base case.