class Solution {
public:
string convertToTitle(int n) {
string s = "";
int tmp;
while (n) {
tmp = n%26;
if (tmp == 0) {
s = 'Z' + s;
n --; //26是Z而不是AZ
} else {
s = char('A'+tmp-1) + s;
}
n = n/26;
}
return s;
}
};
171. Excel表列序号
解法1:从右向左累加
class Solution {
public:
int titleToNumber(string s) {
int len = s.length();
//if (len == 0)
// return 0;
int sum = 0;
for(int i = len-1; i >= 0; i--) {
sum += (s[i] - 'A' + 1)*pow(26, len-i-1);
}
return sum;
}
};
解法2:从左向右累加
class Solution {
public:
int titleToNumber(string s) {
int len = s.length();
//if (len == 0)
// return 0;
int sum = 0;
for(int i = 0; i < len; i++) {
sum = sum*26 + (s[i] - 'A' + 1);
}
return sum;
}
};