天天看點

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

版權聲明:轉載請聯系本人,感謝配合!本站位址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50498759

翻譯

給定一個正整數,傳回它作為出現在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;
    }
};           

繼續閱讀