Q: Implement atoi to convert a string to an integer.
昨天很巧地在《剑指offer》的开篇看到了这个例子,作者举这个例子是为了强调程序的鲁棒性,鼓励我们在写代码之前就想好测试用例,避免程序漏洞导致系统运行崩溃,其实这在前面也提到过,还是那句话,想好所有可能会出现的情况再开始敲。
<span style="color:#333333;">public class Solution {
public int atoi(String str) {
int num = 0;
int i = 0;
if (str.length() == 0){ </span><span style="color:#ff0000;">//空字符串</span><span style="color:#333333;">
return 0;
}
char ch[] = str.toCharArray();
while (i < ch.length && ch[i] == ' '){ </span><span style="color:#ff0000;">//str = " 112233"</span><span style="color:#333333;">
i ++;
}
int t = i;
int count = 0;
while (ch[i] == '+' || ch[i] == '-'){ </span><span style="color:#ff0000;">//str = "+-2"</span><span style="color:#333333;">
i ++;
count ++;
}
if (count > 1){
return 0;
}
int j = i;
while (j < ch.length && Character.isDigit(ch[j])){ </span><span style="color:#ff0000;">//str = " 1122a33"</span><span style="color:#333333;">
j ++;
}
while (i < j) {
if (ch[t] == '-'){
num += (-1) * (ch[i] - 48) * Math.pow(10, j - 1 - i);
}
else{
num += (ch[i] - 48) * Math.pow(10, j - 1 - i);
}
i ++;
}
return num;
}
}</span>