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
------------------------- thinking -----------------------------------------------
very simple, but need to be very careful!!! Easy to fail at edge case!
we need to remember that each count should start from 0 instead of 1, so here n should always minus 1 for the correct index
------------------------- problems ------------------------------------------------
This question is a little different from natural number, because 0 cannot be the first digit of the number, while A is allowed to be at first one here! So be very careful for the while loop in the code, and n's updating in the loop!
------------------------- codes --------------------------------------------------
class Solution {
public:
string convertToTitle(int n) {
string result = "";
n = n - 1;
while (n >= 0) {
result.insert(0, 1, 'A' + n % 26);
n = n / 26 - 1;
}
//result.insert(0, 1, 'A' + n % 26);
return result;
}
};
No comments:
Post a Comment