当前位置:网站首页>Leecode07. Integer inversion -- leecode100 hot questions series

Leecode07. Integer inversion -- leecode100 hot questions series

2021-10-14 05:05:50 Old fellow iron has dried up the code.

I'm Xiao Zhang , Determined to use the most concise code to do the most efficient expression


The following is my personal solution , Each problem includes all solutions as much as possible , And achieve the optimal solution , Welcome to collect ! Leaving a message. !

Portal ——>Leecode Big factory hot topic 100 Tao series problem solution


Problem description

To give you one 32 Signed integer of bit x , Return to x The result of reversing the number part in .
If the integer after inversion exceeds 32 The range of signed integers of bits [−231, 231 − 1] , Just go back to 0.
Suppose the environment doesn't allow storage 64 An integer ( With or without sign ).

Example 1:
Input :x = 123
Output :321

Example 2:
Input :x = -123
Output :-321

Example 3:
Input :x = 120
Output :21

Example 4:
Input :x = 0
Output :0

Tips :
-231 <= x <= 231 - 1


Attached is the complete runnable code

#include "iostream"
#include "algorithm"
#include "cmath"

using namespace std;

class Solution {
    
public:
    int reverse(int x) {
    

        bool flag = false;
        if (x > 0) flag = !flag;

        long long res = 0;
        while(x) {
    
            res = res * 10 + (x % 10);
            x /= 10;
        }
        if(res < -pow(2, 31) || res > pow(2, 31) - 1) return 0;
        return flag ? abs(res) : -abs(res);
    }
};

int main() {
    
    Solution solution;
    cout << solution.reverse(1534236469);
    return 0;
}

版权声明
本文为[Old fellow iron has dried up the code.]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/10/20211002145845252C.html

随机推荐