1. 程式人生 > >leetcode 7 Reverse Integer(翻轉一個有符號的整數)

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/