public class ParseInt {
private static final int MAX = 0x7fffffff;
private static final int MIN = 0x80000000;
public static int parseInt(char[] s) throws Exception {
if(s == null){
throw new Exception("s is null.");
}
if(s.length == 0){
throw new Exception("s is empty.");
}
int result = 0;
int i = 0;
int length = s.length;
boolean negative = false;
int limit = 0;
if(s[i] == '-'){
negative = true;
limit = MIN;
i++;
}else{
limit = -MAX;
}
if(i < length){
result = s[i] - '0';
if((result<0) || (result>9)){
throw new Exception("not valid number.");
}else{
result *= -1;
i++;
}
}
for(; i<length; i++){
int v = s[i] - '0';
if((v<0) || (v>9)){
throw new Exception("not valid number.");
}
if(result < limit/10){
throw new Exception("out of range 1.");
}//ensure no overflow:
result *= 10;
if(result < (limit + v)){
throw new Exception("out of range 2.");
}//ensure no overflow:
result -= v;
}
if(negative){
if(i > 1){
return result;
}else{
throw new Exception("only \"-\" signal.");
}
}else{
return -result;
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
int v = ParseInt.parseInt("-2147483649".toCharArray());
// int v = ParseInt.parseInt("10a45".toCharArray());
System.out.println(v);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
字符串解析为整数
最新推荐文章于 2023-04-14 13:56:56 发布