leetcode 7 Reverse Integer(翻转一个有符号的整数)

题目要求:

给定一个32位有符号整数,返回该整数的反向数字

示例:

Example 1

Input : 123
Output : 321

Example 2

Input : -123
Output : -321

Example 3

Input : 120
Output : 21

思路:

通过示例可以看出主要分为俩种情况;
1、输入是自然数(包括最后一位是0)
直接进行倒序输出即可;

2、输入是负整数
首先,用第0位记录下负号,然后从第1位开始进行倒序,输出即可。

技巧:

本题也可以在整数层面直接进行操作,但是巧用to_string()转换成字符串进行操作
将会更简单,更好理解。

注意!!

为保证最后的结果合法,在输出前要进行判断。

主要代码 ( C++ ):

// leetcode 007
// reverse integer
class Solution {
public:
    int reverse(int x) {
        string str_x(to_string(x)); //convert the type
        if(str_x[0] == '-') // Judge whether the integer is a negative number
           std::reverse(str_x.begin()+1, str_x.end());
        else
            std::reverse(str_x.begin(),str_x.end());
        long long longreversex = stoll(str_x);
        
        if(longreversex > numeric_limits<int>::max() or longreversex < numeric_limits<int>::min())
            return 0; // Make sure the input is legal
        else
            return longreversex;
        
    }
};

原题链接: https://leetcode.com/problems/reverse-integer/

猜你喜欢

转载自blog.csdn.net/qq_37466121/article/details/84982639
今日推荐