Back to Leetcode Go

168. Excel Sheet Column Title

website/content.en/ChapterFour/0100~0199/0168.Excel-Sheet-Column-Title.md

1.7.971.2 KB
Original Source

168. Excel Sheet Column Title

Problem

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"

Problem Summary

Given a positive integer, return its corresponding column title in an Excel sheet.

For example,

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

Solution Approach

  • Given a positive integer, return its corresponding column title in an Excel sheet
  • Easy problem. This problem is similar to the calculation process of short division. It uses base-26 letter encoding. Divide according to short division first, then output the remainders in reverse order.

Code

go

package leetcode

func convertToTitle(n int) string {
	result := []byte{}
	for n > 0 {
		result = append(result, 'A'+byte((n-1)%26))
		n = (n - 1) / 26
	}
	for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
		result[i], result[j] = result[j], result[i]
	}
	return string(result)
}