题意:字符串转整数
解题思路:
1)字符串开头含有除+或-或空格或数字以外的字符,直接返回0;
2)对字符串去除头尾空白;
3)以符号为分割符分割字符串成字符数组,若含有符号,则取取str[1],否则取str[0];,得到要处理的字符串,执行4);
4)判断要处理字符串的长度是否大于最大整数的长度,大于直接返回最大整数或最小整数;小于或等于执行5)
5)计算sum的值,若sum<0且符号为正,返回最大整数,若sum>0且符号为负返回最小整数;(变号说明越界,大于最大整数,结果为负,小于最小整数,结果为正)
package com.lulu.leetcode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* 把字符串转成整数
*/
public class C_MyAtio {
public int myAtoi(String str) {
if (str == null) {
return 0;
}
str = str.trim();
Pattern pattern = Pattern.compile("[\\+|\\-]{0,1}[0-9]+.*");// 合法的字符串
Matcher matcher = pattern.matcher(str);
if (matcher.matches() == false) {
return 0;
}
int flag = 1;
int outIn = 0;
int sum = 0;
String opstString = new String();
if (str.charAt(0) == '-') {// 判断符号正负
flag = -1;
opstString = str.split("[^0-9]+")[1];// 取全为数字的字符串
} else if (str.charAt(0) == '+') {
flag = 1;
opstString = str.split("[^0-9]+")[1];// 取全为数字的字符串
} else {
opstString = str.split("[^0-9]+")[0];// 取全为数字的字符串
}
outIn=flag;
//int len = opstString.length();
int maxLen=(Integer.MAX_VALUE+"").length();
if(opstString.length()>maxLen && flag==1){
return Integer.MAX_VALUE;
}
if(opstString.length()>maxLen && flag==-1){
return Integer.MIN_VALUE;
}
System.out.println("op="+opstString);
int len = opstString.length();
for (int i = 0; i < len; i++) {
sum = sum * 10 + flag * (opstString.charAt(i) - '0');
System.out.println("out="+outIn+"flag"+flag+"sum="+sum);
if (flag == 1 && sum<0) {
sum = Integer.MAX_VALUE;
break;
} else if (flag == -1 && sum>0) {
sum = Integer.MIN_VALUE;
break;
}
}
return sum;
}
/**
* @param args
*/
public static void main(String[] args) {
String string = "-114748364999";
C_MyAtio cAtio = new C_MyAtio();
System.out.println(cAtio.myAtoi(string));
}
}