Excel table column name

1. Demand

  • Given a positive integer, return its corresponding column name in the Excel table.

E.g,

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 
    ...

Example 1:

Input: 1
 Output: "A"

Example 2:

Input: 28
 Output: "AB"

Example 3:

Input: 701
 Output: "ZY"

Two, base conversion method

2.1 Thinking analysis

  1. A ~ Z will be likened to a hexadecimal F. A ~, A ~ is then Z represents a number of 1 to 26, means that the subject to convert the decimal number hexadecimal 26 A ~ Z represent, we use  x_i to Represents the i-th bit of the 26-base system, then:
  2. The general expression:,  the range ......+x_4*26^3+x_3*26^2+x_2*26^1+x_1*26^0=nat this time  x_iis 1~26, so x1 is required. If the remainder of 26 on both sides of the equation is not obtained, x1 cannot be obtained. To solve this problem, you can subtract 1 from both sides of the equation at the same time, so you get ......+x_4*26^3+x_3*26^2+x_2*26^1+(x_1-1)*26^0=n-1, In this way, the range of x1-1 is 0~25, and the remainder of 26 on both sides of the equation can get x1, that is, x1=(n-1)% 26 + 1;
  3. Similarly, for the convenience of finding x2, divide 26 on both sides of the equation at the same time to eliminate x1. Therefore, the method for x2, x3, etc. is to repeat 2, 3;

2.2 Code implementation

class Solution {
    public String convertToTitle(int n) {
        StringBuilder sb = new StringBuilder();
        while(n > 0) {
            n--;
            //这里将'A'看作1
            sb.append((char)(n % 26 + 'A'));
            n = n / 26;
        }
        sb.reverse();
        return sb.toString();
    }
}

2.3 Complexity analysis

  • The time complexity is to O(log_{26}N)convert decimal to 26;
  • The space complexity is O(1), and the return value is not included in the extra space;

3. Learning address

Author: windliang

Link: https://leetcode-cn.com/problems/excel-sheet-column-title/solution/xiang-xi-tong-su-de-si-lu-fen-xi-by-windliang-2/

Guess you like

Origin blog.csdn.net/Sruggle/article/details/113698482