Reverse Integer Leetcode

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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

c++

#include<iostream>
using namespace std;
class Solution
{
public:
    int reverse(int x)
    {
        int temp=0,result=0;
        while(x!= 0) {
            temp =getlast(x);
            x=x/10;
            result=10*result+temp;
        }
        return result;
    }
    int getlast(int x)
    {
        return x%10;
    }
};
int main()
{

    int x;
    cin>>x;
    Solution s;
    cout<<s.reverse(x);
    return 0;
}

python

这里写代码片

猜你喜欢

转载自blog.csdn.net/qq_40477151/article/details/80683051