My easy to understand JAVA solution


  • 38
    M

    Instead of 1 -> A, 26 -> Z, we can assume that 0 -> A, 25 -> Z, and then here comes the base 26 representation, it's similar when you convert a number from base 10 to base 2

    public class Solution {
    public String convertToTitle(int n) {
        String res = "";
        while(n != 0) {
            char ch = (char)((n - 1) % 26 + 65);
            n = (n - 1) / 26;
            res = ch + res;
        }
        return res;
    }
    }

  • 3
    Y

    instead of using 65, using 'A' might be clearer.


  • 2
    I

    Why do you do n = (n - 1)/26 instead of n /= 26?


  • 6
    M

    The idea is this: suppose you have excel title 52 = AZ = A * 26 + Z * 1, where A = 1, Z = 26.
    Now you shift each digit down i.e. A' = 0, and Z' = 25.
    Then 52 = AZ = (A' + 1) * 26 + (Z' + 1) * 1.

    So now you need to find A' and Z'. Z' = (52 - 1) % 26 = 25, which is (n-1)%26 in the code above.
    Now you need to get A' + 1 from 26 * (A' + 1) + (Z' + 1)
    If you simply do n/=26, Z' + 1 will give additional 1. So you will get n = 2 instead of n = 1.
    To avoid this you do n = (n-1)/26


  • 0

    Thanks for sharing! Could do a little improvement using StringBuilder.

        public String convertToTitle(int n) {
            if (n <= 0) return "";
            StringBuilder ret = new StringBuilder();
            while (n-- > 0) {
                ret.append((char) ('A' + (n % 26)));
                n /= 26;
            }
            return ret.reverse().toString();
        }
    

  • 1
    J

    Sounds good. However, I don't think you can remember ASCII to corresponding integer. Using 65 may not be a good choice.


  • 0

    Similar solution:

    private static final int radix = ('Z' - 'A') + 1;
    public String convertToTitle(int n) {
        StringBuilder result = new StringBuilder();
        for (; n-- > 0; n /= radix)
            result.append((char)('A' + (n % radix)));
        return result.reverse().toString();
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.