美文网首页
7-Reverse Integer

7-Reverse Integer

作者: crishawy | 来源:发表于2019-02-18 20:08 被阅读0次

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可能会超出整数范围,此时应当提前判断是否越界!

相关文章

网友评论

      本文标题:7-Reverse Integer

      本文链接:https://www.haomeiwen.com/subject/bmmzeqtx.html