2 Reverse Integer

本文介绍了一个简单的整数反转算法,并提供了详细的实现步骤。包括如何处理负数和溢出的情况,确保程序的健壮性和准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

分析

1 负数怎么处理?

2 超出范围数据怎么处理,如11113 翻转后31111超范围怎么办?

 

处理方案

1 负数先变成正数处理,最后 再加个负号回去;

2 若是超出范围,返回值为0

代码

#include < stdio.h >

#include < limits.h >
#include < float.h >

 int main()
 {
     int m=0 ;
     int x ;
     int reverse( int x );
     scanf("%d\n" , &x );

     m = reverse( x );

      }
 
 int reverse(int x)
 {
     

     int flag = 0;
     long int reg = 0;
     int n = 0;
          //将负数处理为整数
    if(x<0)
     {
         x = -x;
         flag = -1;
     }
     
//翻转输出
     while(x)  
    {  
            reg = reg * 10 + x % 10;  
            x/=10;  
            printf("%d\n",reg);
     }  
        
     //判断是否 数超阈值
     if(reg > INT_MAX || reg < INT_MIN)
     {
            reg = 0;
     }
     
     // 负数变回正数
     if(flag == -1)
     {
         reg = -reg;
     }
    
     return reg;
 }
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狮子座硅农(Leo ICer)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值