LeetCode 168: Excel Sheet Column Title (Easy)

G

Grant Riordan

Guest

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​


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();
    }
}

Continue reading...
 


Join 𝕋𝕄𝕋 on Telegram
Channel PREVIEW:
Back
Top