Friday, August 14, 2015

Excel Sheet Column Title | Leetcode

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 
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases.

---

Solution: Need to be very careful with the boundary conditions. Subtract n by 1 so that 0 -> A, 1 -> B, ..., 25 -> Z.

Example: Input n = 26. First digit is (n - 1) % 26 = 25 -> Z. Answer is AZ.

Example: Input n = 27. First digit is (n - 1) % 26 = 0 -> A. Set n = ((n - 1) / 26) = 1. Second digit is (n - 1) % 26 = 0 -> A. Answer is AA.

Example: Input n = 52. First digit is (n - 1) % 26 = 25 -> Z. Set n = ((n - 1) / 26) = 1. Second digit is (n - 1) % 26 = 0 -> A. Answer is AZ.
public class Solution {
    public String convertToTitle(int n) {
        StringBuilder sb = new StringBuilder();
        while (true) {
            n--;
            sb.append((char) ('A' + (n % 26)));
            if (n < 26) break;
            n /= 26;
        }
        return sb.reverse().toString();
    }
}

No comments: