码迷,mamicode.com
首页 > 其他好文 > 详细

Excel Sheet Column Title (STRING - TYPE CONVERTION)

时间:2015-01-03 08:10:42      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

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)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4199099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!