首页 > 代码库 > Excel Sheet Column Title (STRING - TYPE CONVERTION)
Excel Sheet Column Title (STRING - TYPE CONVERTION)
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‘; } }};
Excel Sheet Column Title (STRING - TYPE CONVERTION)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。