Wins the offer-67 string to Integer
Title:
converting a string to an integer, the request can not use the library function converts the integer string. Value of 0 or a character string is not a valid return value 0
Thinking:
divided into two parts, symbols and numerals
but note that:
- null
- Empty string ""
- Only + -
- There are + -
- Invaild symbol
Own answer:
public class Solution {
public int StrToInt(String str) {
if(str == null || str.length() == 0) return 0;
char[] ch = str.toCharArray();
int res = Int(ch);
return res;
}
private int unsignInt(char[] ch, int start){
int res = 0;
for(int i = start; i < ch.length; i++){
if(ch[i] >= '0' && ch[i] <= '9'){
res *= 10;
res += (ch[i] - '0');
}
else{
res = 0;
break;
}
}
return res;
}
private int Int(char[] ch){
boolean isNegtive = false;
int start = 0;
if(ch[0] == '+'){
start++;
}else if(ch[0] == '-'){
start++;
isNegtive = true;
}
int res = unsignInt(ch, start);
if(isNegtive)
return -res;
else
return res;
}
}
Mistake:
this code does not consider only the sign (although it will directly return 0, but I did not consider itself in an unsigned function to get inside), without considering overflow down
note:
optimization:
public class Solution {
public int StrToInt(String str) {
if(str == null || str.length() == 0) return 0;
char[] ch = str.toCharArray();
int res = Int(ch);
return res;
}
private int Int(char[] ch){
int isNegtive = 1;
int start = 0;
if(ch[0] == '+'){
start++;
}else if(ch[0] == '-'){
start++;
isNegtive = -1;
}
long res = 0;
for(int i = start; i < ch.length; i++){
if(ch[i] >= '0' && ch[i] <= '9'){
res *= 10;
res += isNegtive * (ch[i] - '0');
if(res > 0x7fff_ffff || res < 0x8000_0000){
res = 0;
break;
}
}
else{
res = 0;
break;
}
}
return (int)res;
}
}