leetcode [#8]

目录

题目

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.

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.


解决方案

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
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Solution {
public int myAtoi(String str) {
str = str.trim();
if(str.length() == 0) return 0;
String regex = "[0-9]+";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
if(!m.find()) return 0;
int index = str.indexOf(m.group(0));
if(index > 1){
return 0;
} else if(index == 1){
if(!(str.charAt(0) == '+' || str.charAt(0) == '-')){
return 0;
} else {
if(str.charAt(0) == '+'){
return convert(m.group(0), '+');
} else {
return convert(m.group(0), '-');
}
}
} else {
return convert(m.group(0), '+');
}
}
private static int convert(String str, char pn){
int length = str.length();
if(length > 10 || (length == 10 && str.compareTo("2147483647") > 0)){
return (pn == '+') ? 2147483647 : -2147483648;
}
int result = 0;
for(int i = 0; i < length; i++){
result += Integer.valueOf(String.valueOf(str.charAt(i))) * Math.pow(10, length - i - 1);
}
return (pn == '+') ? result : 0-result;
}
}

注意事项

  1. 使用trim方法去掉所有的两段空格。
  2. 使用正则表达式匹配第一段连贯的数字。
  3. 判断第一段连贯的数字前面是否只有一位,如果超过一位,则肯定不为数字,返回0;如果仅一位,判断是否为“+”或“-”,如果不是,则肯定不为数字,返回0;如果为0位,表示这一段全是数字。
  4. 在3的基础上,统一调用字符串转数字的私有函数。同时考虑正负号、同时考虑溢出问题。