gavanwanggw

导航

LeetCode 168 Excel Sheet Column Title(Excel的列向表标题)

翻译

给定一个正整数,返回它作为出如今Excel表中的正确列向标题。

比如:
    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 

原文

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 

分析

我非常少用Excel。所以题意不是满懂,就先看了看别人的解法。

class Solution {
public:
    string convertToTitle(int n) {
        if (n<=0) return "";
        if (n<=26) return string(1, 'A' + n - 1);
        return convertToTitle( n%26 ?

n/26 : n/26-1 ) + convertToTitle( n%26 ? n%26 : 26 ); } };

然后放到VS中试了一下。

最终知道题目的意思了……

1 ... A
*******
26 ... Z
27 ... AA
*******
52 ... AZ
53 ... BA
*******
702 ... ZZ
703 ... AAA

大神的递归用的真是666,三目运算符也用的恰到优点。不得不佩服呐!

上面採用的是

'A' + n - 1

紧接着。我写了例如以下代码:

#include <iostream>
using namespace std;

string convertToTitle(int n) {
    string title;
    while (n > 0) {
        title = (char)('A' + (--n) % 26) + title;
        n /= 26;
    }
    return title;
}

int main() {
    cout << convertToTitle(702);
    return 0;
}

核心代码

title = (char)('A' + (--n) % 26) + title;

解决的是习惯上都用的是

string title;
title += "X";

这样都是往末尾追加的,可能在前面追加不是非常习惯,只是也是没问题的。

由于有个起始的A在里面,所以后面加的时候一開始要把n减掉1。每次得到最后一个字符,也就是每次除掉一个26,就当作是26进制一样,事实上和十进制是相通的。

代码

class Solution {
public:
    string convertToTitle(int n) {
        string res;
        while (n > 0) {
            res = (char)('A' + (--n) % 26) + res;
            n /= 26;
        }
        return res;
    }
};

posted on 2017-07-19 15:20  gavanwanggw  阅读(251)  评论(0编辑  收藏  举报