https://leetcode.com/problems/reverse-integer/
溢出处理,最简洁形式
class Solution { public: int reverse(int x) { int res=0; while(x!=0){ if(res>INT_MAX/10 || res<INT_MIN/10) return 0; res = res*10 + x%10; x/=10; } return res; } };
利用unsigned,稍微不美观方式
class Solution { public: int reverse(int x) { unsigned int val = abs(x); unsigned int result = 0; while (val) { if (result > ((unsigned int)(1 << 31) - 1) / 10) return 0; result = result * 10 + val % 10; val /= 10; } return (x > 0 ? result : (-1 * result)); } };
关于 INT_MAX 计算:
#include <iostream> using namespace std; int main() { cout << "INT_MAX " << ((unsigned int)(1 << 31) - 1) << endl; cout << (1 << 31) << endl; cout << (unsigned int)(1 << 31) << endl; cout << "INT_MAX " << INT_MAX << endl;; cout << "INT_MIN " << INT_MIN << endl;; cout << "unsigned INT_MAX " << (unsigned int)INT_MAX << endl;; cout << "unsigned INT_MIN " << (unsigned int)INT_MIN << endl;; return 0; }
输出结果
2^31 = 2 147 483 648
INT_MAX 2147483647 -2147483648 2147483648 INT_MAX 2147483647 INT_MIN -2147483648 unsigned INT_MAX 2147483647 unsigned INT_MIN 2147483648
linux宏定义
#define INT_MAX ((int)(~0U>>1)) #define INT_MIN (-INT_MAX - 1) #define UINT_MAX (~0U) #define LONG_MAX ((long)(~0UL>>1)) #define LONG_MIN (-LONG_MAX - 1) #define ULONG_MAX (~0UL) #define LLONG_MAX ((long long)(~0ULL>>1)) #define LLONG_MIN (-LLONG_MAX - 1) #define ULLONG_MAX (~0ULL)
以INT_MAX为例说明:符号整型数,0取反得到全F,右移1位空出符号位,得到最大的符号整型数,无论它是16位平台还是32位平台,都是正确的,其他各个功能都类似。