A*******e 发帖数: 2419 | 1 C++写了个string convertToTitle(int n),先一番数学推导,然后用44行代码才完成
,用到了二分查找,memoization,26进制的itoa。多个循环,要仔细斟酌循环条件。
同样简单水平的平衡二叉树,10行代码搞定。
这俩怎么能是同一级别? |
T*****9 发帖数: 2484 | 2 看成了LendingClub...
【在 A*******e 的大作中提到】 : C++写了个string convertToTitle(int n),先一番数学推导,然后用44行代码才完成 : ,用到了二分查找,memoization,26进制的itoa。多个循环,要仔细斟酌循环条件。 : 同样简单水平的平衡二叉树,10行代码搞定。 : 这俩怎么能是同一级别?
|
d*****c 发帖数: 605 | 3 不需要44行吧,只是要考虑一下z的特殊情况吧。
class Solution {
public:
string convertToTitle(int n) {
string result;
while (n > 0) {
int rest = n%26;
n /= 26;
if (rest == 0) {
result = 'Z'+ result;
n--;
} else {
result = char(rest + 'A' - 1) + result;
}
}
return result;
}
}; |
A*******e 发帖数: 2419 | 4 牛逼,佩服。比我的代码简单多了。这个Z的特殊处理我确实想不到。
那个逆函数也是类似思路?能分享一下吗?
【在 d*****c 的大作中提到】 : 不需要44行吧,只是要考虑一下z的特殊情况吧。 : class Solution { : public: : string convertToTitle(int n) { : string result; : while (n > 0) { : int rest = n%26; : n /= 26; : if (rest == 0) { : result = 'Z'+ result;
|
A*******e 发帖数: 2419 | 5 明白了。这套编码不用0,而是用Z表示10。A还是1,B是2,如此类推。
【在 A*******e 的大作中提到】 : 牛逼,佩服。比我的代码简单多了。这个Z的特殊处理我确实想不到。 : 那个逆函数也是类似思路?能分享一下吗?
|
s****a 发帖数: 794 | 6 class Solution {
public:
string convertToTitle(int n) {
string str;
while (n > 0) {
str.push_back((n-1)%26+'A');
n = (n-1)/26;
}
reverse(str.begin(), str.end());
return str;
}
}; |
h******1 发帖数: 20 | 7 太牛了 这code写的好简介优美
【在 d*****c 的大作中提到】 : 不需要44行吧,只是要考虑一下z的特殊情况吧。 : class Solution { : public: : string convertToTitle(int n) { : string result; : while (n > 0) { : int rest = n%26; : n /= 26; : if (rest == 0) { : result = 'Z'+ result;
|
A*******e 发帖数: 2419 | 8 主要是思路,相当于十进制里,用1到10,而不是0到9,给数字编码。缺点是不能表示0。
其实汉语的数字描述就是这一套。十相当于这里的Z。
一
二
三
...
十
一十一
一十二
...
【在 h******1 的大作中提到】 : 太牛了 这code写的好简介优美
|