1. 字符轉(zhuǎn)整型數(shù)
輸入一個(gè)由數(shù)字組成的字符串,把它轉(zhuǎn)換成整數(shù)并輸出。例如:輸入字符串"123",輸出整數(shù)123塌计。
給定函數(shù)原型int StrToInt(const char *str) ,實(shí)現(xiàn)字符串轉(zhuǎn)換成整數(shù)的功能侯谁,不能使用庫(kù)函數(shù)atoi锌仅。
注意:
- 1.空字符,單個(gè)字符處理
- 2.正負(fù)符號(hào)
- 3.非數(shù)字字符
- 4.最大值最小值溢出問題
private static int strToInt( String str ){
if( str.length() == 0 ){
return 0;
}
if( str.length() == 1 ){
if( ! isNum( str.charAt(0) ) ){
//只有一個(gè)字符墙贱,且是非法字符
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 ){
//正數(shù)溢出
return 0;
}else if( ! isPositive && -val > 0 ){
//負(fù)數(shù)溢出
return 0;
}
weight *= 10;
}
return isPositive ? val : - val;
}
2. 實(shí)現(xiàn)string到double的轉(zhuǎn)換
此題雖然類似于atoi函數(shù)热芹,但畢竟double為64位,而且支持小數(shù)惨撇,因而邊界條件更加嚴(yán)格伊脓,寫代碼時(shí)需要更加注意。
思路:
和轉(zhuǎn)int一樣串纺,不過要注意小數(shù)點(diǎn)丽旅,不能出現(xiàn)多個(gè)小數(shù)點(diǎn)
private static double strToDouble(String str){
if( str.length() == 0 ){
return 0;
}
if( str.length() == 1 ){
if( ! isNum( str.charAt(0) ) ){
//只有一個(gè)字符,且是非法字符
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 ){
//正數(shù)溢出
return 0;
}else if( ! isPositive && -val > 0 ){
//負(fù)數(shù)溢出
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 ){
//正數(shù)溢出
return 0;
}else if( ! isPositive && -val > 0 ){
//負(fù)數(shù)溢出
return 0;
}
weight /= 10;
}
return isPositive ? val : - val;
}