[Leetcode] #7 整數反轉
阿新 • • 發佈:2021-07-15
[Leetcode] #7 整數反轉
給你一個 32 位的有符號整數 x ,返回將 x 中的數字部分反轉後的結果。
如果反轉後整數超過 32 位的有符號整數的範圍[−231, 231− 1]
,就返回 0。
假設環境不允許儲存 64 位整數(有符號或無符號)。
輸入:x = 123
輸出:321
我能想到的有兩種思路。一是通過數學方式反轉,二是通過字串反轉。
解法一:
先以123為例,思考其變化過程(其實就是加減乘除拼出答案,再整理出來)
class Solution { public int reverse(int x) { int res = 0;//x = 123 res*10//0 x%10//3 res = res*10 + x%10;//0 + 3 x = x/10;//12 res*10//30 x%10//2 res = res*10 + x%10 //30 + 2 x = x/10;//1 res*10//320 x%10//1 res = res*10 + x%10 //320 + 1 return res; } }
提取公共部分轉化為迴圈
class Solution { public int reverse(intx) { int res = 0; while(x != 0) { res = (res * 10) + (x % 10); x /= 10; } return res; } }
提交後提示解答錯誤,看評論才知道還需要考慮反轉後是否溢位(-231 <= x <= 231 - 1
)
優化(參考評論)
class Solution { public int reverse(int x) { int res = 0; while(x != 0) {int tmp = res; // 儲存計算之前的結果 res = (res * 10) + (x % 10); x /= 10; // 將計算之後的結果 / 10,判斷是否與計算之前相同,如果不同,證明發生溢位,返回0 if (res / 10 != tmp) return 0; } return res; } }
解法二:
未完待續...