Sunday, April 30, 2017

168. Excel Sheet Column Title

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:

A little bit tricky. When we use mod or divide, we change n to n - 1 such that the mapping becomes:

   0 -> A
   1 -> B
   2 -> C
   ...
   25 -> Z
   26 -> AA
   27 -> AB 



Code:


public class Solution {
    public String convertToTitle(int n) {
        String title = "";
        while (n > 0) {
            n = n - 1;
            title = (char)('A' + n % 26) + title;
            n /= 26;
        }
        return title;
    }
}