Leetcode-168-excel Table column name

This is the 7th day of my participation in Gwen Challenge

[Blog link]

The path to learning at πŸ”

The nuggets home page

[Topic Description

Given a positive integer, return its corresponding column name in the Excel table. For example, 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" Related Topics Mathematical string πŸ‘ 387 πŸ‘Ž 0Copy the code

[η­” 摈]

Leetcode topic link

[making address]

Code link

[introduction]

Idea 1:26 base conversion + special judgment

  • Long time of simple questions, unfortunately, there is still no AC, for the meaning of the question is not enough to understand
  • The overall meaning of the problem is relatively clear, similar to binary conversion
  • The difference is that they don’t have A 0, which means they have the smallest bits of A
  • This can then be converted using a char value
  • In this case, special test case 52 701 1
public String convertToTitle(int columnNumber) {
            String res = "";
            while(columnNumber ! =0) {
                int temp = columnNumber % 26= =0 ? 26 : columnNumber % 26;
                // If the remainder is 0, keep the current position Z and the current operand -26
                if (temp == 26) {
                    columnNumber -= 26;
                }
                columnNumber = columnNumber == 26 ? 1 : columnNumber / 26;
                res = Character.valueOf((char) (temp + 64)).toString() + res;
            }
            return res;
        }
Copy the code


Time complexity O ( l o g 26 c o l u m n N u m b e r ) Time complexity O(log_{26}^{columnNumber})