avatar

LeetCode-7-整数反转

【题目描述】

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

1
2
输入: 123
输出: 321

示例 2:

1
2
输入: -123
输出: -321

示例 3:

1
2
输入: 120
输出: 21

注意:

1
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231,  2311]。请根据这个假设,如果反转后整数溢出那么就返回 0

Java

<解法一>字符翻转,抛异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class leetCode007{    
public int reverse(int x){
String str=Integer.toString(x);
String str1=str;
int mark=1;
if(x<0){
mark=-1;
str1=str.substring(1);
}
try {
return Integer.valueOf((new StringBuilder(str1)).reverse().toString())*mark; }catch (Exception e){
return 0;
}
}
}
/***
substring类在API文档中的描述
substring
public String substring(int beginIndex)返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
示例:

"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)

参数:
beginIndex - 起始索引(包括)。
返回:
指定的子字符串。
抛出:
IndexOutOfBoundsException - 如果 beginIndex 为负或大于此 String 对象的长度。

--------------------------------------------------------------------------------

substring
public String substring(int beginIndex,int endIndex)返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex。
示例:

"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"

参数:
beginIndex - 起始索引(包括)。
endIndex - 结束索引(不包括)。
返回:
指定的子字符串。
抛出:
IndexOutOfBoundsException - 如果 beginIndex 为负,或 endIndex 大于此 String 对象的长度,或 beginIndex 大于 endIndex。
***/

不了解StringBuilder,可以看这篇文章


执行结果:通过

*执行用时 : * 3 ms, 在所有 Java 提交中击败了27.00%的用户

内存消耗 : 36.4 MB, 在所有 Java 提交中击败了5.00%的用户


复杂度分析

时间复杂度:O(n)

空间复杂度:

<解法二>

1
2
3
4
5
6
7
8
9
10
class Solution {
public int reverse(int x) {
long n = 0;
while(x != 0) {
n = n*10 + x%10;
x = x/10;
}
return (int)n==n? (int)n:0;
}
}

疑问:题目要求《 假设我们的环境只能存储得下 32 位的有符号整数 》,long数据类型长度64位,不合题意?

因解法简单,故记录

执行结果:通过

执行用时 :1 ms, 在所有 Java 提交中击败了100.00%的用户

内存消耗 :36.9 MB, 在所有 Java 提交中击败了5.00%的用户


复杂度分析

时间复杂度:O(n)

空间复杂度:

文章作者: yookbu
文章链接: http://www.yookbu.xyz/LeetCode-7-%E6%95%B4%E6%95%B0%E5%8F%8D%E8%BD%AC/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 yookbu
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论