Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0d528cc

Browse files
committed
8
1 parent 9e44104 commit 0d528cc

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

‎8. String to Integer (atoi).java

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
3+
习题:
4+
Implement atoi to convert a string to an integer.
5+
6+
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
7+
8+
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
9+
10+
*/
11+
12+
/*解析
13+
本题考察的东西就是看你思考的全不全面,而且他还没有说具体的规则,我说一下它判定的规则,分为几种情况
14+
1.空串
15+
2.数字之前有空格如:" 123"
16+
3.带符号的字符串 如:"+123"
17+
4.在数字中间夹杂字符或者空格 如:" —12 33" 将要输出 -12 后面舍弃
18+
5.存在溢出问题,这个我在写的时候就很迷茫。下面主要说明这个问题。
19+
20+
因为是int类型的,所以占4个字节,记住 最大的最小的是 -(2^31)-1 ~ 2^31 -1(有一位是符号位,还有一个数字是0)
21+
判断溢出的条件就是,有两种可能,1.结果>最大位/10 2.结果=最大位/10 并且 digit>最大位%10 只有这两种可能,因为一个数位的变化就是增加或者减少10。
22+
23+
代码如下:
24+
*/
25+
class Solution {
26+
public int myAtoi(String str) {
27+
int sybol=1;//符号 0正数 1负数
28+
int result = 0;
29+
//先判断第一个字符
30+
//分情况讨论:
31+
//只有"+""-"
32+
//空""
33+
//非数字,
34+
//纯数字
35+
if(str==null) {
36+
return 0;
37+
}
38+
if(str.charAt(0)=='-'||str.charAt(0)=='+')
39+
if(str.length()==1)
40+
return 0;
41+
else if(str.charAt(0)=='-')
42+
sybol=0;
43+
str=str.sustring(1);
44+
}
45+
return stringToInt(str,sybol);
46+
47+
}
48+
public int stringToInt(String str,int sybol) {
49+
int digit;
50+
int result=0;
51+
//逐一扫描
52+
while(int i = 0;i<str.length();i++) {
53+
digit = str.charAt(i);
54+
//如果是数字的话
55+
if(digit>='0'||digit<='9') {
56+
result = result*10 + digit;
57+
}
58+
else {
59+
return 0;
60+
}
61+
}
62+
if(sybol==0){
63+
result = -result;
64+
}
65+
}
66+
return result;
67+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /