您的位置:首页 > 其它

leetcode(7)Reverse Integer

2015-05-11 18:36 531 查看
题目我就不赘述了,可以上官网看得到。算了还是贴一下把。

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

就是把输入的数值反向输出即可。这里有一个陷阱就是数值溢出的问题。我的代码跟网上别人的不太一样,看到这个题目的我首先想到的就是,把这个int型转换成string型,这样就可以对单个字符操作,这样就很easy了。

而大部分人是从后往前提取数字,然后相加。这样也行。我就把我的代码贴出来

#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
int reverse(int x) {
if (x == 0)cout <<"0";
else if (x > 0){
res = int2str(x);
for (int i = res.size() - 1; i >= 0; i--){//倒序输出
cout << res[i];
}
return 0;
}
else{
x = abs(x);
cout << "-";
res = int2str(x);
for (int i = res.size() - 1; i >= 0; i--){
cout << res[i];
}
}

}
//function:int to string
string int2str(int x){
sprintf_s(t, "%d", x);
string temp = t;
return temp;
}
private:
char t[256];
string res;
};

int main(int argc, char *argv[]){
int n = -123;
string s;
Solution object;
//s=object.int2str(n);
//cout << s << endl;
object.reverse(n);
return 0;
}


结果显示

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: