源码也不是很复杂,除了那个Integer.MAX_VALUE,下面是简化版的手写parseInt()方法。在我看来最核心的代码是:digit = Character.digit(s.charAt(i++), radix);这个平时很少用到。
package com.dalingjia.math;
public class MyInteger {
public static int parseInt(String s){
return parseInt(s, 10);
}
public static int parseInt(String s , int radix){
int result = 0;
int i = 0;
int digit ;
boolean nagitive = false;
int length = s.length();
if(length > 0){
char firstChar = s.charAt(0);
//+,-号
if(firstChar < '0'){
if(firstChar == '-'){
nagitive = true;
}else if (firstChar != '+'){
throw new NumberFormatException();
}
//只有一个符号
if(length == 1){
throw new NumberFormatException();
}
//向后取数值位
i++;
}
while (i < length){
//取字符串的第i个字符转int
digit = Character.digit(s.charAt(i++), radix);
//乘10
result *= radix;
//减数值
result -= digit;
}
}else {
throw new NumberFormatException();
}
return nagitive ? result : -result;
}
public static void main(String[] args) {
System.out.println(parseInt("3221213"));
System.out.println(parseInt("+55645423"));
System.out.println(parseInt("-643123"));
}
}