7. 整數(shù)反轉(zhuǎn)
難度簡(jiǎn)單2715收藏分享切換為英文接收動(dòng)態(tài)反饋
給你一個(gè) 32 位的有符號(hào)整數(shù) x
涯竟,返回將 x
中的數(shù)字部分反轉(zhuǎn)后的結(jié)果。
如果反轉(zhuǎn)后整數(shù)超過 32 位的有符號(hào)整數(shù)的范圍 [?231, 231 ? 1]
殃恒,就返回 0。
假設(shè)環(huán)境不允許存儲(chǔ) 64 位整數(shù)(有符號(hào)或無符號(hào))拳恋。
示例 1:
輸入:x = 123
輸出:321
示例 2:
輸入:x = -123
輸出:-321
示例 3:
輸入:x = 120
輸出:21
示例 4:
輸入:x = 0
輸出:0
提示:
-231 <= x <= 231 - 1
通過次數(shù)659,655
提交次數(shù)1,884,119
Given a signed 32-bit integer x
, return x
with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range [-231, 231 - 1]
, then return 0
.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
Constraints:
-231 <= x <= 231 - 1
解法1:變成字符串驼修,倒序提取放入stringbuffer伟桅,輸出。
public int reverse(int x) {
int result = 0;
String value = String.valueOf(x);
StringBuilder sb = new StringBuilder();
if (value.charAt(0) == '-') {
sb.append('-');
value = value.substring(1);
}
for (int i = value.length() - 1; i >= 0; i--) {
sb.append(value.charAt(i));
}
try {
result = Integer.valueOf(sb.toString());
} catch (Exception e) {
}
return result;
}
image-20210422085029128
解法2:res = res * 10 + x % 10;
image-20210422091016716
class Solution {
public static int reverse(int x) {
boolean neg = ((x >>> 31) & 1) == 1;//符號(hào)位判斷
x = neg ? x : -x;//全部轉(zhuǎn)成負(fù)數(shù)處理
int m = Integer.MIN_VALUE / 10;
int o = Integer.MIN_VALUE % 10;
int res = 0;
while (x != 0) {
if (res < m || (res == m && x % 10 < o)) {//有效數(shù)判斷
return 0;
}
res = res * 10 + x % 10;
x /= 10;
}
return neg ? res : Math.abs(res);
}
}
image-20210422091114921