Given a 32-bit signed integer, reverse digits of an integer.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
==Example==
123→321 -123→-321 120→21
第一時間想到這是經典的取模取餘運算,可是寫的過程當中遇到了不少問題QAQ(這麼簡單一題git
用這個方法最大的難點在於用int類型時處理溢出問題,本來沒有溢出的數字在進行翻轉時頗有可能溢出,最合適的方法是在處理過程當中進行預判函數
Java代碼:this
public static int reverse(int x) { int overFlow = (int)Math.pow(2,31) -1; //overFlow = 2147483646 int underFlow = 0 - (int)Math.pow(2,31); //underFlow = -2147483647 int pop = 0; int result = 0; while(x != 0){ pop = x % 10; if((result>overFlow/10) || (result==overFlow/10 && pop>7)) return 0; if((result<underFlow/10) || (result==underFlow/10 && pop<-8)) return 0; result = result * 10 + pop; //★ x = x/10; } return result; }
題目中要求的溢出條件實際上是針對int型數據的,這題用Java來寫的話其實能夠用long類型code
Java代碼:ip
public int reverse(int x) { long res = 0; //此處用了long while (x != 0) { res = res * 10 + x % 10; x = x / 10; } return (int)res == res ? (int)res : 0; }