/*
* 输入一个表示整数的字符串,把该字符串转换成整数并输出,例如输入字符串"345",则输出整数345。
*
* 需要考虑的问题:1.由于整数可能不仅仅之含有数字,还有可能以'+'或者'-'开头,表示整数的正负。2.处理非法输入。
* 在使用指针之前判断这个指针是不是为空。3.输入的字符串中可能含有不是数字的字符。4.最后一个需要考虑的问题是溢出问题。
*/
public class atoiTest {
public static long atoi(String str) throws Exception {
boolean negative = false;
long value = 0;
if (str == null || str.equals(""))
throw new Exception("null string or the string has no character!");
for (int i = 0; i < str.length(); i++) {
if (i == 0 && (str.charAt(0) == '-' || str.charAt(0) == '+')) {
if (str.charAt(0) == '-') {
negative = true;
}
}
else {
if (str.charAt(i) >= '0' && '9' >= str.charAt(i)) {
value = value * 10 + (str.charAt(i) - '0');
if (value > Integer.MAX_VALUE)
throw new Exception("OUT OF INTEGER RANGE");
}
else
throw new NumberFormatException("not an integer");
}
}
return negative == true ? value * -1 : value;
}
public static void main(String[] args) throws Exception {
atoiTest at=new atoiTest();
String[] str={"0", "-","01", "-1","123","289765","1000000000","-1000000000",
"-1000000000000","+aa","-abc"};
for(int i=0;i<str.length;i++){
System.out.println("字符:"+str[i]);
System.out.println("整数:"+at.atoi(str[i]));
}
}
}
字符串转换成整数
最新推荐文章于 2022-07-10 20:43:58 发布