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
对于n 是26的整数倍的情况下,需要特殊处理,因为发现如果normal的10进制到26进制的转化是错误的。当n是26的整数倍的时候,n纪录的是还剩下多少个26在n中。
class Solution {
public:
string convertToTitle(int n) {
string rst = "";
while (n) {
if (n % 26 == 0) {
rst = 'Z' + rst;
n = n/26-1;
} else {
char tmp = (n%26-1) + 'A';
rst = tmp + rst;
n = n/26;
}
}
return rst;
}
};
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
class Solution {
public:
int titleToNumber(string s) {
//sanity check
if (s.size() == 0) return 0;
int rst = 0;
for (int i = 0; i < s.size(); i++) {
rst = rst*26 + (s[i]-'A' + 1);
}
return rst;
}
};
No comments:
Post a Comment