LeetCode 7 Reverse Integer
LeetCode 7 Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows
解:
#include<stdio.h>
#include<stdlib.h>
#include<climits>
#define BASE 10
int reverse(int x) {
const int MAX=INT_MIN;
int sign;
// div to x=0 x<0 x>0
if(x==0)
{
return 0;
}
if(x>0)
{
sign=1;
x=-x;
}
else
{
sign=-1;
}
int output=0;
while(x!=0)
{
// tmp为负数 为x的取值的最后一位的负数 即为x的对BASE取余的数值
int tmp=x%BASE;
// 如果 输出的结果比MAX-tmp(即为MAX(INT_MIN(int的最小值))+x的取余的数值的正数)再对10取余;如果output比其小则溢出
// 第一次的时候即为output=0的时候 MAX-tmp/BASE 取余为负数 不可能溢出
// 接下来的中output 乘以BASE+tmp(负数) 一定为负数
if(output<(MAX-tmp)/BASE)
{
return 0;
}
else{
output=output*BASE+tmp;
}
x=(x-tmp)/BASE;
}
return sign*abs(output);
}
设计知识
- climits 头文件的使用
- 设置标志
- 问题的划分
climits 头文件
给定各个数据类型的最大的取值范围

浙公网安备 33010602011771号