以前这道题做过,但是复杂度太大,就超过了5%的人,今天想看看别人是怎么写的,于是我知道了一种方法,速度可以提高,还知道了一个string库的新函数
废话不说,先看代码,等会讲解
class Solution {
public:
int reverse(int x) {
long result;
string temp = "";
temp = to_string(x);
if(x<0)
std::reverse(temp.begin()+1,temp.end());
else
std::reverse(temp.begin(),temp.end());
result = stol(temp);
if(result<2147483647&&result > -2147483648) return result;
else return 0;
}
};
再看结果
![e17a20c9777232cfd038ea056c3801e7.png](https://i-blog.csdnimg.cn/blog_migrate/cd81c90ab66c2a4238a4adf9111a71f5.png)
其中的to_string和stol函数是标准库函数
to_string的作用可以把int、float和char啥啥都转化成string
stol则可以把string转化成int
to_string实例:PlayGround
![633cc63e6f8f9d711c1bea428cd994c7.png](https://i-blog.csdnimg.cn/blog_migrate/e133831724b7db2a6c99e7ee1f867153.png)