Excel Sheet Column Title Conversion

Excel Sheet Column Title Conversion

Given a number, convert it to its corresponding Excel column title.

string convertToTitle(int n) {
    string res="";
    while(n) {
        int a = n%26;
        if (a == 0) res+="Z";
        else {
            res += string(1, a+64);
        }
        n/=26;
        // boundary condition
        if (a == 0) --n;
    }
    reverse(res.begin(), res.end());
    return res;
}

The code works by treating this as a base-26 conversion problem. Each digit maps to a letter where 1=A, 2=B, …, 26=Z. The tricky part is handling the case when the remainder is 0, which corresponds to ‘Z’. When this happens, we subtract 1 from the quotient before continuing.

The result gets built backwards, so we reverse it at the end.