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
Solution:
This is a 26-ary system. However if we use 1-26. 26 can not be consistent with other numbers ahead.
For example: 25/26=0, but 26/26=1. So we need to apply 0-based policy in this problem.
Each number from 1-26 minuses 1 to conform A-Z. But new problems occur, AA should be 27
orginally, 27-1=26, 26%26=0. This is incorrect. So every number should minus 1 in each loop to
make sure it's 0-based.
- class Solution {
- public:
- string convertToTitle(int n) {
- string ans;
- while (n--!= 0) {
- ans = char(int('A') + n % 26) + ans;
- n /= 26;
- }
- return ans;
- }
- };
0 意見:
張貼留言