leetcode.com This is the practice of coding interviews for software developers. A total of more than 1,500 coding questions have been posted, and it seems that the same questions are often asked in actual interviews.
Introduction to golang + algorithm I will solve it with go and Python to strengthen the brain.
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
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"
We will solve it with the policy of converting numbers to letters. It is easy to understand if you know ASCII
Since it goes around with 26 characters, divide by 26 and end the loop when it reaches 0.
Finally, res is in reverse order, so it is inverted and returned.
Answer code
class Solution:
def convertToTitle(self, n: int) -> str:
res = ""
while n > 0:
n -= 1 # 26 -> "Z"
res += chr(n % 26 + ord('A'))
n //= 26
return res[::-1]
--I'll write it in Go too!
func convertToTitle(n int) string {
result := ""
for {
if n <= 26 {
result = string(n+64) + result
break
} else {
result = string((n-1)%26+1+64) + result
n = (n - 1) / 26
}
}
return result
}
Recommended Posts