[LeetCode 7] Reverse Integer


[Problem Link]

Description

Given a 32-bit signed integer, reverse digits of an integer.

Example

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

Solution

class Solution {
public:
    int reverse(int x) {
        long rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            rev = rev * 10 + pop;
        }
        if (rev > INT_MAX || rev < INT_MIN) return 0;
        return rev;
    }
};

Summary

  • 網上判斷數值是否溢出有很多不同的方法,經對比我覺得這種最好理解,所以選擇了這一種。INT型佔8個字節,32位。long型佔16個字節,64位。用long型計算出數值,判斷是否在[INT_MIN, INT_MAX]範圍內。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章