Reverse Integer

来源:互联网 发布:安卓手机java编译 编辑:程序博客网 时间:2024/05/21 09:22

Reverse digits of an integer.

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

click to show spoilers.

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.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.


class Solution {public:    int reverse(int x) {        int nFlag=1;long long nTemp=x;if(x<0){           nFlag=-1;   nTemp*=-1; //labs求绝对值不对}  int nArray[10]={0};int nCount=0;while(nTemp){           nArray[nCount]=nTemp%10; //321   nTemp/=10;           ++nCount;}long long lResult=0;for(int i=0;i<=nCount-1;++i){           lResult*=10;   lResult+=nArray[i];}        lResult*=nFlag;if(lResult>INT_MAX && nFlag==1){return 0;}if(lResult<INT_MIN && nFlag==-1){return 0;}    return  lResult;            }};


0 0
原创粉丝点击