DEV Community

Grant Riordan
Grant Riordan

Posted on

LeetCode 168: Excel Sheet Column Title (Easy)

Approach

This problem is essentially a base-26 conversion, where the "digits" are the 26 letters of the alphabet (A–Z).

Like any base conversion, we process the least significant digit first — meaning we figure out the last letter of the result before the first.

  • Use the modulo operator (% 26) to find the remainder, which tells us the current character.

  • Insert each character at the front of the string (or reverse later), since we’re building the result from right → left.

  • After each step, divide columnNumber by 26 to move on to the next "digit."

  • Important: decrement columnNumber at the start of each loop (columnNumber--) because Excel columns are 1-based, while our alphabet mapping is 0-based.


Example Flow (columnNumber = 28)

Iteration 1

  • Input: 28
  • columnNumber-- → 27
  • Remainder: 27 % 26 = 1
  • Character: 'A' + 1 = 'B'
  • Result: "B"
  • Update columnNumber: 27 / 26 = 1

Iteration 2

  • columnNumber-- → 0
  • Remainder: 0 % 26 = 0
  • Character: 'A' + 0 = 'A'
  • Result: "AB"
  • Update columnNumber: 0 / 26 = 0 → stop

✅ Final result = "AB"

We can verify manually:

  • 27 = 1 full cycle (A → Z) + 2 more columns (AA, AB).

Code

 csharp public class Solution { public string ConvertToTitle(int columnNumber) { var result = new StringBuilder(); while (columnNumber > 0) { columnNumber--; // shift into 0-based int remainder = columnNumber % 26; result.Insert(0, (char)('A' + remainder)); columnNumber /= 26; } return result.ToString(); } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)