题意:字符串转整型。
1.输入为空输出0;
2.输入超过边界值,输出边界值;
3.前面带空格忽略掉;
4.可能带有‘+’,‘-’字符;
5.包含非数字字符的情况,舍去后面的。
package edu.jnu;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
// write your code here
Main m = new Main();
System.out.println(m.myAtoi(" -0012a42"));
System.out.println(m.myAtoi("010"));
System.out.println(m.myAtoi("2147483648"));
System.out.println(m.myAtoi(" -1123u3761867"));
System.out.println(m.myAtoi("9223372036854775809"));
}
public int myAtoi(String str){
// 字符串为空输出0
if(str == null || str.equals("") )
return 0;
int left = 0;
int right = str.length() - 1;
//去掉前面的空格
while (left < str.length()){
if(str.charAt(left) == ' ')
left++;
else
break;
}
// 标记正负数
boolean isPostive = true;
if(str.charAt(left) == '-' || str.charAt(left) == '+'){
if (str.charAt(left) == '-')
isPostive = false;
//去掉符号
left++;
}
if(left > right)//如果是"-",返回
return 0;
long ans = 0;
int i;
for(i = left;i <= right;i++){
//如果出现了数字以外的字符,或者数字超过int范围
if(!(str.charAt(i) >= '0' && str.charAt(i) <= '9') || i - left > 10)
break;
else
ans *= 10;
ans += str.charAt(i) - '0';
}
if (!isPostive)
ans = -ans;
//超出边界的情况
if(ans > (long)Math.pow(2,31) - 1)
ans = (long)Math.pow(2,31) - 1;
if(ans < -(long)Math.pow(2,31))
ans = -(long)Math.pow(2,31);
return (int)ans;
}
}