題目:

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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

 

思路:

問題非常單純,只要將數值進行反轉即可.

但是如果過程溢位(超出int範圍)則回傳0.

最簡單常見是將x轉為string在進行位元反轉.

若用整數進行運算,最單純是增大空間並在中間判斷是否溢位.

但是在真實的32bit環境無法使用此方案.(因實際狀況中即便宣告long 仍會只有int的空間,因此無法判別)

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
int reverse(int x) {
    long int ans = 0;
    while(x){
        ans *= 10;
        ans += x%10;
        if(ans > INT_MAX || ans < INT_MIN)  return 0;
        x /= 10;
    }
    return (int)ans;
}
arrow
arrow
    文章標籤
    leetcode Easy
    全站熱搜
    創作者介紹
    創作者 Lung-Yu,Tsai 的頭像
    Lung-Yu,Tsai

    Lung-Yu,Tsai 的部落格

    Lung-Yu,Tsai 發表在 痞客邦 留言(0) 人氣()