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

My original solution using StringBuilder

public class Solution {
    public String convertToTitle(int n) {
        StringBuilder sb = new StringBuilder();
        while (n > 26) {
            n--;
            char val = (char) (n % 26 + 'A'); // 1 = 'A', so we decrement n by 1 above 
            sb.append(val);
            n /= 26;
        }
        sb.append((char) (n - 1 + 'A'));
        return sb.reverse().toString();
    }
}

One line recursive solution

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

Analysis

This is a typical problem about decimal conversion
The first solution is to construct digit from the ending position
The second solution is to construct digit from the beginning position

results matching ""

    No results matching ""