把一個字符串轉換成int類型,比如“123” --> 123
這道題目主要考查邊界情況及非法輸入的處理,c++跟Java處理起來不一樣,Java是不存在整數比Integer.MAX_VALUE還大的數,Java會將溢出的數自動進行處理成合法的值,負數也是同理,劍指offer49題用c++實現,直接比較了一下正數或負數跟最大正整數和最小負整數的值,Java這樣比較是不行的。參考Integer("123455")的構造方法,實現如下:
public class _49_StrToInt {//把一個字符串轉換成int類型,比如“123” --》 123
public static boolean valid = false;
public static boolean coreFlag=false;
public static int strToInt(String num){
if(num == null || num.length() == 0){
valid = false;
return 0;
}
int a = 0;
if(num.charAt(0)=='+'){//
a = core(num,'+');
}else if(num.charAt(0) == '-'){
a = core(num,'-');
}else if(num.charAt(0) >= '0' && num.charAt(0)<='9'){
a = core(num,'0');
}else{
valid = false;
return 0;
}
if(coreFlag){
valid = true;
return a;
}else{
valid = false;
return 0;
}
}
public static int core(String num, char flag){
int i=0;
if(flag == '+' ){
i = 1;
}
if(flag == '-'){
i=1;
}
int a = 0;
int temp =a;
for(;i<num.length();i++){
if(!(num.charAt(i) >='0' && num.charAt(i)<='9' )){
coreFlag = false;
return 0;
}
temp =a ;
if(flag != '-'){
a = a*10;
a += (int)(num.charAt(i)-'0');
if( temp > a){//若當前數小,說明溢出
coreFlag = false;
return 0;
}
}else {
a = a*10;
a -= (int)(num.charAt(i)-'0');/////負數直接相減,不用乘以-1
if( temp < a){//負數應該越加越小,若當前數比之前數大,說明溢出
coreFlag = false;
return 0;
}
}//
}
coreFlag = true;
return a;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = strToInt("-21474836"); //-2147483648
if(valid){
System.out.println(a);
}
}
}
分別輸入最大最小值或者比其還大或還小的值,以及其他非法數字格式測試,輸出正確。