Leetcode刷题(7.整数反转)

一.题目

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例1:

输入: 123
输出: 321

示例2:

输入: -123
输出: -321

示例3:

输入: 120
输出: 21

注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

二.代码(C)

版本一:

int reverse(int x)
{
    int i,j;
    double y=0;
    int temp;
    int flag=0;
    if (x==-pow(2,31))
    {
        return 0;
    }
    else if (x<0)
    {
        x=-x;
        flag=1;
    }
    for (i=1;i<32;i++)
    {
        if (pow(10,i)>x &&pow(10,i-1)<=x)
        {
            break;
        }
    }
    //printf("%d\n",i);
    for(j=i;j>0;j--)
    {
        temp = x/(int)(pow(10,j-1));
        if (temp*pow(10,i-j)>pow(2,31)-1)
        {
            return 0;
        }
        //printf("temp=%d\n",temp);
        y=y+temp*pow(10,i-j);
        //printf("pow=%f\n",pow(10,i-j));
        //printf("y=%d\n",y);
        x = x- temp * (pow(10,j-1));
        //printf("x=%d\n",x);
    }
    if (flag)
    {
        y=-y;
    }
    if (y<-pow(2,31) || y>pow(2,31)-1)
    {
        return 0;
    }
    return y;
}

版本二

int pow1(int a,int b)
{
    int y=1;
    for (;b>0;b--)
    {
        y = y*a;
    }
    return y;
}

int reverse(int x)
{
    int i,j;
    double y=0;
    int temp;
    int flag=0;
    if (x==-pow1(2,31))
    {
        return 0;
    }
    else if (x<0)
    {
        x=-x;
        flag=1;
    }
    for (i=1;i<32;i++)
    {
        //printf("pow1=%d\n",pow1(10,i));
        if (pow(10,i)>x &&pow(10,i-1)<=x)
        {
            break;
        }
    }
    //printf("%d\n",i);
    for(j=i;j>0;j--)
    {
        temp = x/(int)(pow1(10,j-1));
        if (temp*pow(10,i-j)>pow(2,31)-1)
        {
            return 0;
        }
        //printf("temp=%d\n",temp);
        y=y+temp*pow1(10,i-j);
        //printf("pow=%f\n",pow(10,i-j));
        //printf("y=%d\n",y);
        x = x- temp * (pow1(10,j-1));
        //printf("x=%d\n",x);
    }
    if (flag)
    {
        y=-y;
    }
    if (y<-pow(2,31) || y>pow(2,31)-1)
    {
        return 0;
    }
    return y;
}

三.提交记录

在这里插入图片描述
在这里插入图片描述

四.备注

算法本身较简单,主要问题在考虑溢出和正负的判断,代码有很大的进步空间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值