Excel Sheet Column Title
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 C++版:
class Solution {
public:
string convertToTitle(int n) {
string ret = "";
while(n)
{
ret = (char)((n-)%+'A') + ret;
n = (n-)/;
}
return ret;
}
};
Python版:
1,10进制转成26进制,但需要注意先减1。
2,chr(i):返回整数i对应的ASCII字符。与ord()作用相反。
3,逆序返回可以直接用res[::-1]。
4,python中string类型的数据没有append(var), insert(index,var),pop(var)等list所拥有的方法,需要特别的注意.
5,python不用像c++那样声明数据类型,但也可以声明,如string=''(字符串),list=[](列表),tuple=(1,1,2,3,)(元组声明后不能更改)
class Solution:
# @param {integer} n
# @return {string}
def convertToTitle(self, n):
flag=n
string=''
while n!=:
rem=(n-)%
n=(n-)/
rem=chr(rem+)
string+=(rem)
return string[::-]
Excel Sheet Column Number
Related to question Excel Sheet Column Title
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进制,因为'A'以1开头而不是0,因此要“+1”
class Solution {
public:
int titleToNumber(string s) {
int len=s.size();
int res=;
for(int i=;i<len;i++)
res=res*+s[i]-'A'+;
return res;
}
};