文章目录
  1. 1. Question:String to Integer
  2. 2. SourceCode:
    1. 2.1. s1
    2. 2.2. s2

Question:String to Integer

Implement atoi to convert a string to an integer.

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.

Note:

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.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace 

character is found. Then, starting from this character, takes an optional initial plus or minus sign 

followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are 

ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no 

such sequence exists because either str is empty or it contains only whitespace characters, no 

conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of

the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

SourceCode:

s1

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
50
51
52
53
54
55
56
57
58
59
//笔者提交版本;耗时:8ms;
public class Solution {
public int myAtoi(String str) {
if(null == str || str.isEmpty() || "" == str||"+".equals(str)||"-".equals(str)){
return 0;
}
//" -0012a42"
String tmpStr = str.trim();
int index = 0;//第一个不不符合数字格式的坐标,
int len = tmpStr.length();
//遍历确定index
for(int i = 0 ; i<len ;i++){
char ch = tmpStr.charAt(i);
index = i+1;
if('-' == ch || '+' == ch){
if(i == 0){
continue;
}else{
index = i;
break;
}
}
if(ch <'0' || ch >'9'){
index = i;
break;
}
}
//" -11919730356x"
index = index > 12 ? 12 :index;
//数字位数超出Int 直接截断;截断是注意保留的剩余部分绝对值要大于int。int位数加符号“+(-)”一共11位,取12 防止最高位是1或者2
String tmpResult = tmpStr.substring(0,index);
long result = 0;
try{
//用long转满足 大于或小于int_max_value ,取最值;
result = Long.parseLong(tmpResult);
}catch(Exception e){//捕获 "+" "-"的异常//eg:input : "+-2"
result = 0;
}
//result = Long.parseLong(tmpResult);
if(result > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
if(result < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
return (int)result;
}
}

s2

1
2
//该版本参考了Discuss,还没看Discuss;耗时:ms;
//待写
文章目录
  1. 1. Question:String to Integer
  2. 2. SourceCode:
    1. 2.1. s1
    2. 2.2. s2