Excel Sheet Column Title (Leetcode 168) - Top Coding Question

Mani
Mani
Educating everyone with the beauty of programming!!

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"

 

Constraints:

  • 1 <= columnNumber <= 231 - 1

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
 * Time Complexity: O(n)
 * Space Complexity: constant .
 **/
class Solution {
    public String convertToTitle(int col) {
        StringBuilder sb = new StringBuilder();
        while(col > 0) {
            int x = col % 26;
            int rem = x == 0 ? 26 : x;
            sb.append((char)(64 + rem));
            col = (col - rem)/ 26 ;
        }
        return sb.reverse().toString();
    }
}
Drop your comments below for any questions or comments. For full list of must learn top interview questions Click Here: Must Learn Top Interview Questions

Rating: