【题目】
Implement atoi to convert a string to an integer.
用自己的方法实现将字符串转换成整型数字
【思路】
1、转换过程中有两个状态,start_flag=0表示转换未开始,start_flag=1表示转换已开始;
2、start_flag=0时,若出现‘-’,‘+’,‘数字’,则start_flag设为1,转换开始;若出现空格,则结束本次循环,继续查询;若出现其他字符,则返回0;
3、start_flag=1时,若出现数字,则更新结果,若出现其他字符则终止转换,返回当前结果;其中,要判断是否当前数值的加入是否会超出范围;
【Java代码】
public class Solution_8_string_to_integer {
public int myAtoi(String str){
int result = 0;
int start_flag = 0;
int negiv_flag = 0;
for(int i = 0 ; i < str.length() ; i++){
if(start_flag == 0 && (str.charAt(i)=='-' || str.charAt(i)=='+' || (str.charAt(i)>='0' && str.charAt(i)<='9'))){
start_flag = 1;
if(str.charAt(i) == '-'){
negiv_flag = 1;
continue;
}
else if(str.charAt(i) == '+'){
negiv_flag = 0;
continue;
}
}
if(start_flag == 1){
if(!(str.charAt(i)>='0' && str.charAt(i)<='9'))
return negiv_flag == 1?-result:result;
else{
if(negiv_flag == 1 && (result > 214748364 || (result == 214748364 && str.charAt(i)-'0' > 8)))
return -2147483648;
if(negiv_flag == 0 && (result > 214748364 || (result == 214748364 && str.charAt(i)-'0' > 7)))
return 2147483647;
result = result*10 + str.charAt(i)-'0';
}
}else{
if(str.charAt(i) != ' ')
return 0;
else
continue;
}
}
return negiv_flag == 1?-result:result;
}
}