Excel Sheet Column Title Problem


Description

LeetCode Problem 168.

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

For example:

1
2
3
4
5
6
7
8
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28 
...

Example 1:

1
2
Input: columnNumber = 1
Output: "A"

Example 2:

1
2
Input: columnNumber = 28
Output: "AB"

Example 3:

1
2
Input: columnNumber = 701
Output: "ZY"

Example 4:

1
2
Input: columnNumber = 2147483647
Output: "FXSHRXW"

Constraints:

  • 1 <= columnNumber <= 2^31 - 1


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
    string convertToTitle(int n) {
        string ans;
        int p;
        while (n > 0) {
            p = n % 26;
            n = n / 26;
            if (p == 0) {
                p = 26;
                n --;
            }
            ans += 'A' + p - 1;
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};




Related Posts

Additive Number Problem

LeetCode 306. Additive number is a string whose digits can...

Largest Number Problem

LeetCode 179. Given a list of non-negative integers nums, arrange...

Excel Sheet Column Title Problem

LeetCode 168. Given an integer columnNumber, return its corresponding column...

Excel Sheet Column Number Problem

LeetCode 171. Given a string columnTitle that represents the column...

Valid Number Problem

LeetCode 65. Given a string s, return true if s...

Text Justification Problem

LeetCode 68. Given an array of strings words and a...