LeetCode 7. Reverse Integer ( C )-Easy

題目為給定一個整數 ( INT ) ,反轉此整數 ( INT )。

題目與範例如下

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

 

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
 

Constraints:

-231 <= x <= 231 - 1

我的解題策略為,每次從 x 取出最後一位數加到 total ( 先對 total x 10 進位 ) ,在加之前都先判別是否溢位。這邊有個小技巧 if ( total * 10 < INT_MAX ) 要寫成 if ( total < INT_MAX/10 ) ,不然在判別時就會溢位了。

下方為我的程式碼

int reverse(int x){
    int total = 0,max = INT_MAX/10,min = INT_MIN/10;
    while(x != 0){
        if(total<=max && total >= min){
            total *= 10;
            total += x%10;
            x/=10;
        }
        else
            return 0;
    }
    return total;
}

下方為時間與空間之消耗

Runtime: 4 ms, faster than 55.81 % of C online submissions for Reverse Integer.

Memory Usage: 5.5 MB, less than 94.79 % of C online submissions for Reverse Integer.

下一題連結 : LeetCode 8. String to Integer (atoi)( C )-Medium

Add a Comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *