Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

I. Title Description:

168. Excel table column Names – LeetCode (leetcode-cn.com)

Given an integer columnNumber, return its corresponding column name in the Excel table.

Such as:

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

Example 1:

Input: columnNumber = 1 Output: "A"Copy the code

Example 2:

Input: columnNumber = 28 Output: "AB"Copy the code

Example 3:

Input: columnNumber = 701Copy the code

Example 4:

Input: columnNumber = 2147483647 Output: "FXSHRXW"Copy the code

Tip:

  • 1 <= columnNumber <= 2^31 - 1

Ii. Analysis of Ideas:

  1. First of all this can be understood as a base conversion problem, from decimal to 26 base

  2. Note that the first digit is 1 and the last digit is 26(whereas the decimal digit is 0 and the last digit is 9).

  3. In this case, the columnNumber (-1) is set to 0, and the remainder of the columnNumber (26) is added to the char buffer

  4. Another point to note is that if the remainder is 0 for A, the ASCII code of A is 65, so the remainder +65 is converted to char and put in the buffer

  5. Finally, reverse the buffer output to String

Iii. AC Code:

class Solution { public String convertToTitle(int columnNumber) { StringBuilder sb = new StringBuilder(); while (columnNumber>0){ columnNumber--; sb.append((char)(columnNumber%26 + 65)); columnNumber/=26; } sb.reverse(); return sb.toString(); }}Copy the code

Iv. Summary:

I don’t have anything to write, so I’ll switch to base 26, and notice that it’s [1,26], not [0,25].

【 范文 】

Excel table column Name – Excel table column name – LeetCode (leetcode-cn.com)