您的位置:首页 > 其它

LeetCode - Excel Sheet Column Title

2015-01-23 17:31 225 查看
Excel Sheet Column Title

2015.1.23 17:20

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB

Solution:

  The code below is self-explanatory. It is a piecewise function.

  Total time is O(log(n)), only in that the logarithm base here is 26.

Accepted code:

// 1CE, 4WA, 1AC, so careless
class Solution {
public:
string convertToTitle(int n) {
long long int n1 = n;
long long int base = 26;
int len = 1;

--n1;
while (n1 >= base) {
n1 -= base;
base *= 26;
++len;
}

string s;

base /= 26;
while (base > 0) {
s.push_back(n1 / base + 'A');
n1 %= base;
base /= 26;
}

return s;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: