7. Reverse IntegerTotal Accepted:
126996 all submissions:
538523 Difficulty:
Easy
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return-321
Has a thought about this?
Here is some good questions to ask before coding. Bonus points for if you have already thought through this!
If the last digit are 0, what should the output being? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer and then the reverse of 1000000003 overflows. How should handle such cases?
For the purpose of this problem, assume a your function returns 0 when the reversed integer overflows.
Determines whether the bounds are exceeded by the size of each digit and int boundary value.
classSolution { Public: intReverseintx) {intneg=0; if(x<0) {neg=1; X=0-x; } inty=0; while(1) { inttmp1=x/Ten; inttmp2=x%Ten; if(neg!=1) { if(y>214748364) {y=0; Break; } Else if(y==214748364&& tmp2>7) {y=0; Break; } } Else { if(y>214748364) {y=0; Break; } Else if(y==214748364&& tmp2>8) {y=0; Break; }} y=y*Ten+TMP2; X=TMP1; if(x==0) Break; } if(neg==1) y=0-y; returny; }};
But there is a problem: if x=-2147483648, the first step to reverse the time has crossed the border. Therefore, a long long type is used to ignore the case of the rollover value, and then decide whether to cross the bounds.
classSolution { Public: intReverseintx) {intneg=0; Long inty=0, tx=x; if(tx<0) {neg=1; TX=0-TX; } while(1) { inttmp1=tx/Ten; inttmp2=tx%Ten; Y=y*Ten+TMP2; TX=TMP1; if(tx==0) Break; } if(neg==1) y=0-y; if(Y>int_max | | y<int_min)return 0; returny; }};
Leetcode:reverse Integer