【leetcode】Excel Sheet Column Title & Excel Sheet Column Number (easy)

时间:2024-12-16 21:06:32

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

思路:

相当于10进制转26进制。与一般不一样的是10进制对应的是0 - 9。而这个26进制对应的是 A(1)- Z(26), 没有0。

我的代码:

string convertToTitle(int n) {
string ans;
while(n != )
{
int num = n % ;
n /= ;
if(num != )
{
ans.push_back(num - + 'A');
}
else
{
ans.push_back('Z');
n--;
}
}
reverse(ans.begin(), ans.end());
return ans;
}

大神精简的代码:

string convertToTitle(int n) {
string res;
char tmp;
while(n){
n -= ; //这里相当于把A-Z表示成了0-25就与一般的表达一样了
tmp = 'A' + n % ;
res = tmp + res;
n /= ;
}
return res;
}

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

For example:

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

思路:26进制转10进制。 以AAA为例   AAA = A * 26+ A * 261 + A * 260;

int titleToNumber(string s) {
int ans = ;
int factor = ;
while(!s.empty())
{
ans = ans + (s.back() - 'A' + ) * factor;
s.pop_back();
factor *= ;
}
return ans;
}

大神精简版的:

int result = ;
for (int i = ; i < s.size(); result = result * + (s.at(i) - 'A' + ), i++);
return result;