Excel Sheet Column Title

Excel Sheet Column Title

Sergei Golitsyn

https://leetcode.com/problems/excel-sheet-column-title/

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"

Solution:

In this problem, we will work with a few basic concepts. We will use char operations and will convert an integer into a character. Also, we will deeply work with '%' and '/' operations.

To solve this problem, we can start from the last char. We get the rest of columnNumber %26. Why do we use 26? Because we have 26 English characters. We add the last character to our result. And then, we can divide columnNumber.

And repeat this operation again and again, till the columnNumber != 0;

  public String convertToTitle(int columnNumber) {
    if (columnNumber <= 26) {
      return String.valueOf ((char)((columnNumber + 'A') - 1));
    }
    StringBuilder sb = new StringBuilder();

    int overTimes = columnNumber;

    while(overTimes > 0){
      int rest =  overTimes % 26;
      if (rest == 0) {
        sb.append('Z');
        overTimes = overTimes / 26 - 1;
      } else {
        sb.append(((char)((rest + 'A') - 1)));
        overTimes /= 26;
      }
    }

    return sb.reverse().toString();
  }


Report Page