当需要用到int的最大和最小值进行比较时,头文件<limits.h>中定义了宏:INT_MAX和INT_MIN可以拿来直接用:
#include <limits.h>#include<iostream>using namespace std;int main(){ cout <<"INT_MAX:"<< INT_MAX << endl << "INT_MIN:" << INT_MIN << endl;}比如
Reverse digits of an integer.
Example1: x = 123, return 321
Example2:x = -123, return -321
实现:
class Solution {public: int reverse(int x) { int flag = 0; long int result = 0; if(x/10 == 0) return x; if(x < 0){ x *= -1; flag = 1; } while(x){ result = result * 10 + x%10; x = x/10; } if(flag) result *= -1; if(result > INT_MAX || result < INT_MIN) return 0; return result; }};注:其中,为了防止整数越界,需要先将结果存入long中,然后在与最大最小值进行比较。