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<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<cmath>
#include<string>
#include<string.h>
#include<set>
#include<map>
#include<queue>
#include<stack>
using namespace std;

int main()
{
     int x;
     cin>>x;
     //使用类似pop和push操作
     int temp;
     int pop;
     int rev = 0;
     while(x)
     {
          pop = x%10;
          x /= 10;
          if(rev > INT_MAX/10 || (rev == INT_MAX/10 && pop>7))
          {
              cout<<0;
              return 0;
          }
          else if(rev < INT_MIN/10 || (rev == INT_MIN/10 &&pop<-8))
          {
              cout<<0;
              return 0;
          }
          rev = rev*10 + pop;
     }
     cout<<rev;
     return 0;
}

本题总结:
1.c++使用INT_MAX取最大INT值,为-232~232-1,即-2147483648~2147483647
2.数字回文操作,可以使用类似pop、push操作
pop = x %10;
rev = rev10 + pop;
x /= 10;
注意这里的rev = rev
10 + pop可能会超出整数范围,此时应当提前判断是否越界!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容