关于这道题目,题目本身还是不错的,真正核心的代码也就那么两行,大部分代码基本都在做非法输入的检查。
具体代码如下:
package com.zhumq.leetcode;
import java.util.Scanner;
import org.junit.Test;
public class StringToInteger {
public Integer stringToInteger(String str) {
//如果为空直接返回null
if(str == null) return null;
//去掉空格后转成字符数组
char[] ch = str.trim().toCharArray();
//如果只输入了空格同样返回null
if(ch.length == 0) return null;
boolean isMinus = false;
int index = 0;
//首个字符是否为'-'或'+'
if(ch[index] == '-') {
isMinus = true;
index++;
}else if(ch[index] == '+') {
index++;
}
//如果只有负号位时返回null
if(index > ch.length-1) return null;
//如果后面的输入字符合法则转化成整数
int num = 0;
while(index <= ch.length-1) {
//输入不合法时返回null
if(ch[index] < '0' || ch[index] > '9') {
return null;
}
//对合法字符进行转换
num = 10*num +(ch[index] - '0');
index++;
}
//加上符号位
num = isMinus?(-1*num):num;
return Integer.valueOf(num);
}
@Test
public void test1() {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String str = sc.next();
System.out.println(stringToInteger(str));
}
sc.close();
}
}