This is the 27th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Topic describes
Given an integer columnNumber, return its corresponding column name in the Excel table. For example: A ->1
B -> 2
C -> 3. Z ->26
AA -> 27
AB -> 28. The sample1: Enter: columnNumber =1Output:"A"The sample2: Enter: columnNumber =28Output:"AB"The sample3: Enter: columnNumber =701Output:"ZY"The sample4: Enter: columnNumber =2147483647Output:"FXSHRXW"Tip:1 <= columnNumber <= 231 - 1Source: LeetCode//leetcode-cn.com/problems/excel-sheet-column-titleCopyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.Copy the code
Ideas & CODE
1. 26 Base operation
It was the first time I encountered this kind of base problem, and it was amazing
Modulo and division operations
[a-z] corresponds to [1-26], and the range is equivalent to 1*26^0 to 26 *26^0
AA – ZZ] [] [27-702, corresponding range rather then 26 * 26 ^ 0 + 0 * ^ 1 ~ 26 * 26 26 * 26 ^ ^ 0 + 1
A base 26 number can be expressed as:
a1 * 26^0 + a2 * 26^1 + a3 * 26^2 + ... = n
Copy the code
If you take the modulo of both sides, you get this
n = a1
Copy the code
If you divide both sides, the result is:
a2 * 26^0 + a3 * 26^1 + ... = n
Copy the code
That’s the same thing as moving this 26 number one to the right
In this case, you just need to do the multiplication and division until n becomes 0 to get the result. The result of each multiplication can be added to ‘A’ to get the corresponding character
Special treatment: minus one operation
As you can see, the number in the problem starts at 1, so the range of 26 letters is [1-26], but the range of 26 letters is [0-25]. To avoid this, we must subtract one from the number every time we loop.
- example
Char (15 + ‘A’); char (15 + ‘A’); char (15 + ‘A’); char (15 + ‘A’); char (15 + ‘A’); char (15 + ‘A’
public String convertToTitle(int columnNumber) {
StringBuilder res = new StringBuilder();
while (columnNumber > 0) {
columnNumber--;
int mod = columnNumber % 26;
res.append((char) (mod + 'A'));
columnNumber /= 26;
}
return res.reverse().toString();
}
Copy the code