Leetcode Problem.7—Reverse Integer

来源:互联网 发布:纯阳网络wenchunyang 编辑:程序博客网 时间:2024/06/06 00:41

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

My C++ solution!

 int reverse(int integer)  {    if(integer==0x80000000)return 0;long long temp=0;int len=0;bool flag=(integer>=0)?false:true;integer=(integer>=0)?integer:(-integer);long long xiao=1;int integer1=integer;while(integer1){len++;xiao*=10;integer1=integer/xiao;}xiao/=10;int jinwei=1;while(len){temp+=integer/xiao*jinwei;if(flag&&temp>0x80000000)return 0;else if(!flag&&temp>0x7fffffff)return 0;jinwei*=10;integer%=xiao;len--;xiao/=10;}temp=flag?-temp:temp;return temp;}


0 0