1. 字符转整型数
输入一个由数字组成的字符串,把它转换成整数并输出。例如:输入字符串"123",输出整数123。
给定函数原型int StrToInt(const char *str) ,实现字符串转换成整数的功能,不能使用库函数atoi。
注意:
- 1.空字符,单个字符处理
- 2.正负符号
- 3.非数字字符
- 4.最大值最小值溢出问题
private static int strToInt( String str ){
if( str.length() == 0 ){
return 0;
}
if( str.length() == 1 ){
if( ! isNum( str.charAt(0) ) ){
//只有一个字符,且是非法字符
return 0;
}
return str.charAt(0) - '0';
}
boolean isPositive = true;
boolean hasSymbol = true;
char firstChar = str.charAt(0);
if( firstChar == '+' ){
isPositive = true;
}else if( firstChar == '-' ){
isPositive = false;
}else{
isPositive = true;
hasSymbol = false;
}
int weight = 1;
int minIndex = hasSymbol ? 1 : 0;
int val = 0;
for( int i = str.length() - 1; i >= minIndex; i-- ){
char ch = str.charAt(i);
if( ! isNum( ch ) ){
//非法字符
return 0;
}
int curr = ch - '0';
curr *= weight;
val += curr;
if( isPositive && val < 0 ){
//正数溢出
return 0;
}else if( ! isPositive && -val > 0 ){
//负数溢出
return 0;
}
weight *= 10;
}
return isPositive ? val : - val;
}
2. 实现string到double的转换
此题虽然类似于atoi函数,但毕竟double为64位,而且支持小数,因而边界条件更加严格,写代码时需要更加注意。
思路:
和转int一样,不过要注意小数点,不能出现多个小数点
private static double strToDouble(String str){
if( str.length() == 0 ){
return 0;
}
if( str.length() == 1 ){
if( ! isNum( str.charAt(0) ) ){
//只有一个字符,且是非法字符
return 0;
}
return str.charAt(0) - '0';
}
boolean isPositive = true;
boolean hasSymbol = true;
char firstChar = str.charAt(0);
if( firstChar == '+' ){
isPositive = true;
}else if( firstChar == '-' ){
isPositive = false;
}else{
isPositive = true;
hasSymbol = false;
}
double weight = 1;
int minIndex = hasSymbol ? 1 : 0;
double val = 0;
int pointIndex ;
for( pointIndex = minIndex; pointIndex < str.length(); pointIndex++ ){
if( str.charAt(pointIndex) == '.' ){
break;
}
}
for( int i = pointIndex - 1; i >= minIndex; i-- ){
char ch = str.charAt(i);
if( ! isNum( ch ) ){
//非法字符
return 0;
}
int curr = ch - '0';
curr *= weight;
val += curr;
if( isPositive && val < 0 ){
//正数溢出
return 0;
}else if( ! isPositive && -val > 0 ){
//负数溢出
return 0;
}
weight *= 10;
}
weight = 0.1;
for( int i = pointIndex + 1; i < str.length(); i++ ){
char ch = str.charAt(i);
if( ! isNum( ch ) ){
//非法字符
return 0;
}
double curr = ch - '0';
curr *= weight;
val += curr;
if( isPositive && val < 0 ){
//正数溢出
return 0;
}else if( ! isPositive && -val > 0 ){
//负数溢出
return 0;
}
weight /= 10;
}
return isPositive ? val : - val;
}
网友评论