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

String Without Aaa Or Bbb Problem

LeetCode 984. Given two integers a and b, return any...

Shifting Letters Problem

LeetCode 848. You are given a string s of lowercase...

Positions Of Large Groups Problem

LeetCode 830. In a string sof lowercase letters, these letters...

Orderly Queue Problem

LeetCode 899. You are given a string s and an...

Number Of Lines To Write String Problem

LeetCode 806. You are given a string s of lowercase...

Masking Personal Information Problem

LeetCode 831. You are given a personal information string s,...