leetcode_168 Excel表列名称

1. 题意

根据列的数值大小,转换成对应的字符串。
Excel表列名称

2. 题解

数学题,但是没想明白。抄一抄官解了。

首先
n u m b e r = ∑ i = 0 n − 1 a i ∗ 2 6 i , 1 ≤ a i ≤ 26 number = \sum_{i = 0}^{n-1} a_i * 26^i, 1 \le a_i \le26 number=i=0n1ai26i,1ai26

与进制的模并不一样,所以要往进制上靠。那就左右两边同时减去1。
n u m b e r − 1 = a 0 − 1 + ∑ i = 1 a i ∗ 2 6 i    ( 1 ) a 0 − 1 = ( n u m b e r − 1 ) % 26 n u m b e r ′ = n u m b e r − a 0 26 n u m b e r ′ = a 1 + ∑ i = 2 n − 1 a i ∗ 2 6 i − 1   ( 2 ) n u m b e r i = n u m b e r i − 1 − a i 26 number - 1 = a_0 - 1 + \sum_{i = 1}a_i *26^i \ \ (1)\\ a_0-1 = (number - 1) \%26 \\ number' = \frac{number - a_0}{26} \\ number' = a_1 +\sum _{i=2}^{n-1}a_i * 26^{i-1} \ (2)\\ number_i = \frac {number_{i-1} - a_i} {26} number1=a01+i=1ai26i  (1)a01=(number1)%26number=26numbera0number=a1+i=2n1ai26i1 (2)numberi=26numberi1ai
(1)式与(2)式相似,同理可以求得 a i a_i ai 直到 n u m b e r i number_i numberi为0。

这时可以解出

class Solution {
public:
    string convertToTitle(int columnNumber) {
        
        string str;
        
        for ( ;columnNumber; ) {
            
            int a0 = (columnNumber - 1)%26 + 1;
            char c = 'A' +  a0 - 1;

            str.insert(str.begin(), c);
            columnNumber = (columnNumber - a0) / 26;
        }
        

        return str;
    }
};

化简
n 26 = ⌊ n + k 26 ⌋ , 0 ≤ k ≤ 25 n u m b e r i = n u m b e r i − 1 − a i 26 = ⌊ n u m b e r i − 1 − a i + a i − 1 26 ⌋ = ⌊ n u m b e r i − 1 − 1 26 ⌋ a 0 − 1 = n u m b e r − 1 c = ′ A ′ + a 0 − 1 n u m b e r ′ = n u m b e r − 1 26 \frac{n}{26} = \lfloor \frac{n+k}{26}\rfloor, 0 \le k \le 25 \\ number_i = \frac {number_{i-1} - a_i}{26} = \lfloor \frac {number_{i-1} - a_i + a_i - 1}{26} \rfloor = \lfloor \frac{number_{i-1} - 1}{26}\rfloor \\ a_0-1 = number -1 \\ c = 'A' + a_0 -1 \\ number' = \frac {number -1}{26} 26n=26n+k,0k25numberi=26numberi1ai=26numberi1ai+ai1=26numberi11a01=number1c=A+a01number=26number1
最后结果

class Solution {
public:
    string convertToTitle(int columnNumber) {
        
        string str;
        
        for ( ;columnNumber; ) {
            --columnNumber;
            char c = 'A' + columnNumber % 26;    
            str.insert(str.begin(), c);
            columnNumber /= 26;
        }
        

        return str;
    }
};

你可能感兴趣的:(leetcode,leetcode)