Monday, April 6, 2015

Excel Sheet Column Title

Problem:
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 

Solution:
class Solution {
public:
     // Solution 1:
    /*string convertToTitle(int n) {
        string sol;
        int factor = 26;
        while (n > 0) {
            if (n%factor == 0) {
                sol += 'Z';
                n = (n/factor) - 1; 
            } else {
                sol += 'A' + (n%factor) - 1;
                n = n/factor;
            }
        }
        reverse(sol.begin(), sol.end());
        return sol;
    }

    // Solution 2: Without string reverse.
    string convertToTitle(int n) {
        string sol;
        int factor = 26;
        while (n > 0) {
            if (n%factor == 0) {
                sol.insert(0, 1, 'Z');
                n = (n/factor) - 1; 
            } else {
                sol.insert(0, 1, 'A' + (n%factor) - 1);
                n = n/factor;
            }
        }
        return sol;
    }*/

    //Solution 3: Make string from char and insert.
    string convertToTitle(int n) {
        string ans;
        do {
            n--;
            char c = 'A' + (char)(n % 26);
            ans = string(1, c) + ans;
            n/=26;
        } while(n);
        
        return ans;
    }
};

===== Another attempt ====
string convertToTitle(int n) {
        string ans;
        while (n > 0) {
            char to_append;
            if (n % 26 == 0) {
                to_append = 'Z';
                n = (n / 26) - 1;
            } else {
                to_append = (n % 26) + 'A' - 1;
                n = n / 26;
            }
            ans = string(1, to_append) + ans;
        }
        return ans;
    }

No comments:

Post a Comment