QUESTION
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
FIRST TRY
class Solution { public: string convertToTitle(int n) { int remain = n%26; n /= 26; string ret = ""; char ch; while(1) { if(n == 0 && remain == 0) { return ret; } else if(n == 0) { ch = getChar(remain); return ch + ret; } ch = getChar(remain); ret = ch + ret; //char -> string, direct concat remain = n%26; n /= 26; } return ret; } char getChar(int n) { if(n != 0) return ‘A‘+ n - 1; else return ‘Z‘; } };
Result: Wrong
Input: 26
Output: "AZ"
Expected: "Z"
SECOND TRY
注意了余数为0的情况
class Solution { public: string convertToTitle(int n) { int remain = n%26; n /= 26; string ret = ""; char ch; while(1) { if(n == 0 && remain == 0) { return ret; } else if(n == 0) { ch = getChar(n,remain); return ch + ret; } ch = getChar(n,remain); ret = ch + ret; //char -> string, direct concat remain = n%26; n /= 26; } return ret; } char getChar(int& n, int remain) { if(remain != 0) return ‘A‘+ remain - 1; else { n -= 1; return ‘Z‘; } } };
时间: 2024-10-04 17:52:40