数学题,但是没想明白。抄一抄官解了。
首先
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=0∑n−1ai∗26i,1≤ai≤26
与进制的模并不一样,所以要往进制上靠。那就左右两边同时减去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}
number−1=a0−1+i=1∑ai∗26i (1)a0−1=(number−1)%26number′=26number−a0number′=a1+i=2∑n−1ai∗26i−1 (2)numberi=26numberi−1−ai
(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⌋,0≤k≤25numberi=26numberi−1−ai=⌊26numberi−1−ai+ai−1⌋=⌊26numberi−1−1⌋a0−1=number−1c=′A′+a0−1number′=26number−1
最后结果
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;
}
};