zoukankan      html  css  js  c++  java
  • Excel Sheet Column Title (STRING

    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';
            }
        }
    };
  • 相关阅读:
    http
    jquery
    wsgi
    urls控制器
    模板template
    ORM
    C++中获取汉字拼音首字缩写/全拼及生僻字的处理
    C语言函数strstr
    CString 成员函数用法
    判断字符串中是否存在中文
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4199099.html
Copyright © 2011-2022 走看看