Skip to content

168 Excel Sheet Column Title ✅

Leetcode

::: tip 💡 Hint: There are 26 characters in ["A","Z"], and each can be mapped to an integer. :::

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

For example:

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

Example 1:

Input: columnNumber = 1
Output: "A"

Example 2:

Input: columnNumber = 28
Output: "AB"

Example 3:

Input: columnNumber = 701
Output: "ZY"

Example 4:

Input: columnNumber = 2147483647
Output: "FXSHRXW"

Variant Implement a function that converts a spreadsheet column id to the corresponding integer, with "A" corresponding to 1

C# Solution

using System;
using System.Collections.Generic;
using System.Text;

namespace Algorithms.Simple
{
  public class ExcelSheelColumnTitle
  {
    public static IEnumerable<char> Calculate(int v)
    {
      var colTitle = new StringBuilder();

      while (v != 0)
      {
        colTitle.Insert(0, (char)('A' + (v - 1) % 26));
        v = (v - 1) / 26;
      }

      return colTitle.ToString();
    }
  }
}

C# Tests

using Algorithms.Simple;
using Xunit;

namespace AlgorithmTests.Simple
{
  public class ExcelSheelColumnTitleTests
  {
    [Fact]
    public void TestEqual()
    {
      Assert.Equal("A", ExcelSheelColumnTitle.Calculate(1));
      Assert.Equal("AB", ExcelSheelColumnTitle.Calculate(28));
      Assert.Equal("ZY", ExcelSheelColumnTitle.Calculate(701));
      Assert.Equal("FXSHRXW", ExcelSheelColumnTitle.Calculate(2147483647));
    }
  }
}