SoFunction
Updated on 2025-03-01

Detailed explanation of the Excel table column name example of Go Java algorithm

Excel table column name

Give you an integer columnNumber, returning its corresponding column name in the Excel table.

For example:

A -> 1

B -> 2

C -> 3

...

Z -> 26

AA -> 27

AB -> 28

...

  • Example 1:

Input: columnNumber = 1

Output: "A"

  • Example 2:

Input: columnNumber = 28

Output: "AB"

  • Example 3:

Input: columnNumber = 701

Output: "ZY"

  • Example 4:

Input: columnNumber = 2147483647

Output: "FXSHRXW"

hint:

1 <= columnNumber <= 231 - 1

Method 1: Mathematics (Java)

According to the question, we can see that 'A' = chr(1+ord('A')-1) =》2 = chr(2+ord('A') -1) , so it starts from the single bits like the decimal system.

Using a loop, first find the remainder. If the remainder is 0, it means that it is a multiple of 26. You need columnNumber-= 26, then set the remainder = 26, and then find the second last digit. . . Until the highest bit, that is, the first bit on the left, find the remainder to 0, the spliced ​​string is flipped.

class Solution {
    public String convertToTitle(int columnNumber) {
        StringBuffer sb = new StringBuffer();
        while (columnNumber != 0) {
            columnNumber--;
            ((char)(columnNumber % 26 + 'A'));
            columnNumber /= 26;
        }
        return ().toString();
    }
}

cloumnNumber: convert the number of bits in hexadecimal

Time complexity: O (log26(columnNumber))

Space complexity: O(1)

Method 1: Mathematics (Go)

The specific methods and ideas have been expressed in the above article. Please refer to the above article for details.

Turn decimal to hexadecimal, take the remainder first and divide until num == 0. Since 1 corresponds to A, the starting num - 1

  • First create a hexadecimal number and its corresponding letter map
  • Take the remainder of 26 for the total number, and get the corresponding letters through map. Note that when the remainder is 0, the remainder is 26.
  • Subtract the remainder and divide it by 26. This step mainly eliminates the single digits, moves the ten digits to the single digits, and then performs the same processing as above.
func convertToTitle(columnNumber int) string {
    ans := []byte{}
    for columnNumber > 0 {
        columnNumber--
        ans = append(ans, 'A'+byte(columnNumber%26))
        columnNumber /= 26
    }
    for i, n := 0, len(ans); i < n/2; i++ {
        ans[i], ans[n-1-i] = ans[n-1-i], ans[i]
    }
    return string(ans)
}

cloumnNumber: convert the number of bits in hexadecimal

Time complexity: O (log26(columnNumber))

Space complexity: O(1)

The above is the detailed explanation of the Excel table column name example of Go Java algorithm. For more information about the Excel table column name of Go Java algorithm, please pay attention to my other related articles!