leetcode每日一題-7:整數反轉
鏈接
整數反轉
題目

分析
題目不是很難,但是細節很多,并且不允許存盤64位整數,需要考慮很多的東西.在之后的代碼部分逐一分析.
代碼
C++
class Solution {
public:
int reverse(int x) {
int f = 1;
// 標記一下正數還是負數
if(x < 0) f = -1;
int maxn = INT_MAX;
int inf = INT_MIN;
int res = 0;
// 負數的最小值反轉后超出了范圍,提前范圍,避免下面的abs報錯
if(x == inf) return 0;
x = abs(x);
while(x > 0)
{
// 依次取出最低位
int t = x % 10;
// 如果當前res * 10 > maxn,那么就超出了范圍
if(res > maxn / 10) return 0;
// 不超范圍就更新res的值
res = res * 10 + t;
// 更新x的值
x /= 10;
}
// 回傳帶標志位的res
return f * res;
}
};
Java
官方題解沒有轉化成正數求解,而是一起計算
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
if (rev < Integer.MIN_VALUE / 10 || rev > Integer.MAX_VALUE / 10) {
return 0;
}
int digit = x % 10;
x /= 10;
rev = rev * 10 + digit;
}
return rev;
}
}
作者:LeetCode-Solution
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/356055.html
標籤:其他
上一篇:【力扣】47. 全排列 II
