168 Excel Sheet Column Title ✅¶
::: 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:
Example 1:
Example 2:
Example 3:
Example 4:
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));
}
}
}