Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
一刷:
測(cè)試:
- "+-2"
- " 123 456"
- " -11919730356x"
- "2147483647"
- "-2147483648"
- "2147483648"
- "-2147483649"
- "+2"
這題的難點(diǎn)在于所有的corner case, 面試時(shí)碰到要仔細(xì)和面試官多交流
- 判斷str是否為空或者長(zhǎng)度是否為0
- 處理前后的space收叶,也可以用str = str.trim();
- 嘗試求出符號(hào)sign
- 處理數(shù)字
(1) 假如char c = str.charAt(index)是數(shù)字骄呼,則定義int num = c - '0', 接下來(lái)判斷是否越界
1). 當(dāng)前 res > Integer.MAX_VALUE / 10判没,越界蜓萄,根據(jù)sign 返回 Integer.MAX_VALUE或者 Integer.MIN_VALUE
2). res == Integer.MAX_VALUE / 10時(shí), 根據(jù)最后sign和最后一位數(shù)字來(lái)決定是否越界澄峰,返回Integer.MAX_VALUE或者 Integer.MIN_VALUE
3). 不越界情況下嫉沽,res = res * 10 + num - 處理非數(shù)字和‘+’, ‘-’俏竞,直接跳到6.
- 返回結(jié)果 res * sign
public class Solution {
public int myAtoi(String str) {
int res = 0;
if(str == null || str.length() == 0) return res;
int neg = 1, digit;
for(int i=0; i<str.length(); i++){
str = str.trim();
if(str.charAt(i)=='-' && i == 0) neg = -1;
else if(str.charAt(i)=='+' && i == 0) neg = 1;
else if(str.charAt(i)<'0' || str.charAt(i)>'9') return neg*res;
else{
digit = str.charAt(i) - '0';
int overflow = overflow(res, digit, neg);
if(overflow>0 ) return Integer.MAX_VALUE;
else if(overflow<0) return Integer.MIN_VALUE;
res = res*10 + digit;
}
}
return res*neg;
}
private int overflow(int res, int digit, int sign){
if(sign > 0){
if(res>Integer.MAX_VALUE/10) return 1;
else if(res == Integer.MAX_VALUE/10 && digit > 7) return 1;
}
else{
if(res>Integer.MAX_VALUE/10) return -1;
else if(res == Integer.MAX_VALUE/10 && digit > 8) return -1;
}
return 0;
}
}