欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Reverse Integer

程序员文章站 2022-03-15 20:33:08
...

题目:
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.

注意:题中已经给出,超范围时返回0.int型数据是4字节,32位,INT_MAX = 2^31-1,INT_MIN= -2^31.如果想表示的整数超过了该限值,可以使用长整型long long 占8字节64位。

class Solution {
public:
    int reverse(int x) {
     long long y,z=0;
     while(x!=0)
     {
         y=x%10;
         x=x/10;
         z=z*10+y;
     }
    if(z>INT_MAX||z<INT_MIN)
        return 0;
     else
     return z;
    }
};
相关标签: 编程基础