https://leetcode.com/problems/reverse-integer/description/html
Given a 32-bit signed integer, reverse digits of an integer.python
Example 1:ios
Input: 123 Output: 321
Example 2:git
Input: -123 Output: -321
Example 3:app
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.less
1 // 2 // main.cpp 3 // LeetCode 4 // 5 // Created by Hao on 2017/3/16. 6 // Copyright © 2017年 Hao. All rights reserved. 7 // 8 9 #include <iostream> 10 #include <cstring> 11 #include <vector> 12 using namespace std; 13 14 class Solution { 15 public: 16 int reverse(int x) { 17 int result = 0; 18 int sign = 1; 19 20 if (x < 0) { 21 sign = -1; 22 x = abs(x); 23 } 24 25 while (x != 0) { 26 if (result > (INT_MAX - x % 10) / 10) // it's ok coz input would not be reverse of INT_MIN 27 return 0; 28 29 result = result * 10 + x % 10; 30 x /= 10; 31 } 32 33 return result * sign; 34 } 35 }; 36 37 int main(int argc, char* argv[]) 38 { 39 Solution testSolution; 40 string result; 41 42 vector<int> iVec = {123, -123, 120, 2147483647, -2147483648, 0}; 43 44 /* 45 321 46 -321 47 21 48 0 49 0 50 0 51 */ 52 for (auto i : iVec) { 53 cout << testSolution.reverse(i) << endl; 54 } 55 56 return 0; 57 }
int
type is unbounded.sys.maxsize
.int
values is available as sys.maxint
:>>> sys.maxint 9223372036854775807
-sys.maxint - 1
as shown here.1 class Solution: 2 def reverse(self, x: int) -> int: 3 result = 0 4 sign = 1 5 6 if x < 0: 7 sign = -1 8 x = abs(x) 9 10 while x != 0: 11 if result > ( 2**31 - ( x % 10 ) ) // 10: # be careful of floor division (integer division) 12 return 0 13 14 result = result * 10 + x % 10 15 x //= 10 # be careful of floor division (integer division) 16 17 return result * sign 18 19 def reverse2(self, x: int) -> int: 20 # [begin:end:step] - leaving begin and end off and specifying a step of -1, it reverses a string. 21 s = str( abs( x ) ) 22 x_reverse = int( s[ ::-1 ] ) if x > 0 else (- int( s[ ::-1 ] ) ) 23 24 if ( ( x_reverse >= - 2**31 ) and ( x_reverse <= 2**31 - 1 ) ): 25 return x_reverse 26 else: 27 return 0