反转数字
123 ---》321
-123----》-321
上面的两个例子可以写出一个程序
if(x>0){
while(x%10!=0){
ret=10*ret+x%10;
x/=10;
}
}
else if(x<0){
}
考虑边界条件 x=0,就 返回0
x=100, 返回x=1
x翻转以后出现越界溢出。
对程序进行修改:
if(x>0){
while(x%10!=0){
ret=10*ret+x%10;
x/=10;
}
//x=100这种情况
while(x%10=0&&x!=0){
x/=10;
ret=x;
}
}
优化:
bool is_positive=x>0?true:false;
x=abs(x);
while(x>0){ //判断循环的次数,x/10=0,那么就是最后一位了
ret=10*ret+x%10;
x=x/10;
std::cout<<x<<std::endl;
}
if(!is_positive) ret*=-1;
加上越界的考虑:写溢出函数
bool isOverFlow(int x){
x=abs(x);
// bool ret=true;
std::cout<<1;
if(x<999999999) return false;
std::cout<<2;
for(int cmp=463847412;cmp!=0;cmp/=10,x/=10){
std::cout<<3<<std::endl;
if ( x%10 > cmp%10 )
{
return true;
} else if (x%10 < cmp%10)
{
return false;
}
}
return false;
}
class Solution {
/******
*先判断正负,
* 考虑x=100 .翻转后x=1
*****/
public:
int reverse(int x) {
int ret=0;
if(x==0) return 0;
if(isOverFlow(x)) return 0;
bool is_positive=x>0?true:false;
std::cout<<x<<std::endl;
x=abs(x);
while(x>0){ //判断循环的次数,x/10=0,那么就是最后一位了
ret=10*ret+x%10;
x=x/10;
std::cout<<x<<std::endl;
}
if(!is_positive) ret*=-1;
return ret;
}
private:
bool isOverFlow(int x){
x=abs(x);
// bool ret=true;
std::cout<<1;
if(x<999999999) return false;
std::cout<<2;
for(int cmp=463847412;cmp!=0;cmp/=10,x/=10){
std::cout<<3<<std::endl;
if ( x%10 > cmp%10 )
{
return true;
} else if (x%10 < cmp%10)
{
return false;
}
}
return false;
}
};
改进:1.取绝对值进行优化,战胜0.9%
查资料,改进算法:
直接对产生的值进行判断:
ret>INT_MAX/10 就会发生溢出, ret为负 ret<INT_MIN/10就会发生溢出 战胜37%
class Solution {
/******
*先判断正负,
* 考虑x=100 .翻转后x=1
*****/
public:
int reverse(int x) {
int ret=0;
int n=0;
while(x!=0){
if(ret>(INT_MAX/10)||ret<(INT_MIN/10)) return 0;//发转出来的最后一位一定小于7,所以只需要判断到倒数第二位
ret=10*ret+x%10;
x/=10;
}
return ret;
}
};