[LeetCode] 7. Reverse Integer


Reverse digits of an integer.

Example1:
x = 123, return 321
Example2:
x = -123, return -321

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.


</br>

Solution

This solution is pretty straightforward, we only have to get the last digit of the number and output it. To achieve which, it is obvious to use division; by applying x % 10, and the remainder is the value of that digit.

Other than this, we also have to take care the overflow problem. How can we identify whether there is a overflow? Because the input is a 32-bit signed integer, we can then use a 64-bit long to store the output and compare to the int version of the same output. If two values are not the same, then we can conclude that there should be a overflow.

The code is shown as below.

Java

public class Solution {
    public int reverse(int x) {
        
        int pos = Math.abs(x);
        int divide = pos, len = 0;
        long output = 0;
        
        while (divide > 0){
            divide = divide / 10;
            len ++;
        } 
        
        for (int i = 0; i < len; i++){
            output += (pos % 10) * Math.pow(10,len-i-1);
            pos = pos / 10;
        }
        
        int overflow = (int) output;
        if ( overflow != output )
            return 0;
            
        if(x<0)
            output = -output;
            
        return (int)output;
    }
}

</br>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容