1. 程式人生 > >LeetCode-007: Reverse Integer

LeetCode-007: Reverse Integer

題目:

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

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

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,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

題意:

把給定數字翻轉它的數位。

思路:

翻轉後溢位int型別輸出0!!!從最右邊非0位開始翻轉!!!~~~不想做題隨便水水,好歹養成每日一題的習慣,好想有個妹紙一起打卡學習啊。白日做夢繫列emmm

Code:

class Solution {
public:
    int reverse(int x) {
        if(x==0) return 0;
        int flag1=0,flag2=0;
        long long y=0,max=((long long)1<<31)-1,min=-(1<<31);
        if(x<0){
            flag1=1;
            x=-x;
        }
        while(x){
            int t=x%10;
            if(!flag2&&!t){
                x/=10;
                continue;
            }
            flag2=1;
            y=y*10+t;
            x/=10;
        }
        if(flag1) y=-y;
        return y>max||y<min?0:y;
    }
};