public static void main(String[] args) {
System.out.println("开始输入:");
//从键盘输入字符串
Scanner input = new Scanner(System.in);
//获取键盘输入的字符串
String str = input.nextLine();
System.out.println("结束");
//字符串转字符数组
char[] num = str.toCharArray();
//使用StringBuffer对象存储拼接后的数字
StringBuffer hire = new StringBuffer();
//如果字符串以“-”开头
if(str.startsWith("-")) {
//在拼接前给字符串加上符号
hire.append("-");
for (int i = 0; i < num.length; i++) {
hire.append(num[i]);
}
}else {
//Character.isDigit(a) 判断a是否是数字,如果是,则返回true,否则返回false
//判断字符串的开否是否是数字,如果不是,直接输出0
if(!Character.isDigit(num[0])) {
System.out.println(0);
}else {
//如果是数字,则对数字进行拼接
hire.append("-");
for (int i = 0; i < num.length; i++) {
hire.append(num[i]);
}
}
}
System.out.println(hire);
}
2.借鉴大神的实现方式
public class Demo {
public static void main(String[] args) {
System.out.println("开始输入:");
//从键盘输入字符串
Scanner input = new Scanner(System.in);
//获取键盘输入的字符串
String str = input.nextLine();
System.out.println("结束");
int myAtoi = myAtoi(str);
System.out.println(myAtoi);
}
public static int myAtoi(String str) {
// 合法性判断
if (str.isEmpty()) return 0;
// 正负号标记
int sign = 1;
// 转换值
int base = 0;
// 索引位数
int i = 0;
// 剔除开始空白字符
while (str.charAt(i) == ' ')
i++;
// 判断正负号
if (str.charAt(i) == '-' || str.charAt(i) == '+')
sign = str.charAt(i++) == '-' ? -1 : 1;
// 索引有效数字字符
while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
// that statement is used to test if the num is bigger than INT_MAX after the str[i] is handled, if base > INT_MAX/10,
// then base10+ str[i] -‘0’> base10>INT_MAX, or when base== INT_MAX/10, that means all the places are the same as INT_MAX except the ones place, so str[i]>‘7’ is needed.
// 上面这段是LeetCode国外站对下面代码的解释。
// 简单来说就是
// 如果`base > MAX_VALUE/10`,那么`base*10 + new_value` > `base*10` > `MAX_VALUE`。这个应该很容易理解,这种情况下就会发生溢出。
// 若`base == INT_MAX/10`,而且`new_value = str.charAt(i++) - '0'`大于`7`,也会发生溢出。因为`MAX_VALUE = 2147483647`
if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)) {
return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
// 计算转换值,str.charAt(i++) - '0'可以把字符串转换成数字
base = 10 * base + (str.charAt(i++) - '0');
}
// 计算结果值
return base * sign;
}