Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Title Description
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
Enter a description:
Enter a string including alphanumeric symbols, can be null
Output Description:
If it is a legitimate expression of the digital value is returned, otherwise 0
Example 1 Input
+2147483647
1a33Export
2147483647
0
Solution one: learning Sao operation of a title in front of a brother
public class Solution {
public int StrToInt(String str) {
if(str==null||str.length()==0) return 0;
try{
int result = Integer.valueOf(str);
return result;
}catch(Exception e){
return 0;
}
}
}
Solution two: write your own traversal conversion
Ideas: feeling a little low
public class Solution {
public int StrToInt(String str) {
if(str==null||str.length()==0) return 0;
char c = str.charAt(0);
long result;
boolean flag = true;
if(c>='0'&&c<='9') result = c-'0';
else if(c=='+') result = 0;
else if(c=='-'){
flag = false;
result = 0;
}else return 0;
if(str.length()>11) return 0;
for(int i=1;i<str.length();i++){
c = str.charAt(i);
if(c>='0'&&c<='9'){
result = result*10+(c-'0');
}else{
return 0;
}
}
if(flag==true&&result<=(long)Integer.MAX_VALUE){
return (int)result;
}
if(flag==false&&(-result)>=(long)Integer.MIN_VALUE){
return (int)-result;
}
return 0;
}
}
Solution three: elegant code yourself
public class Solution {
public int StrToInt(String str) {
if(str==null||str.length()==0) return 0;
char c = str.charAt(0);
long result = 0;
long flag = 1;
if(c=='-') flag=-1;
if(str.length()>11) return 0;
for(int i=((c=='+'||c=='-')?1:0);i<str.length();i++){
c = str.charAt(i);
if(c>='0'&&c<='9'){
result = (result<<1)+(result<<3)+(c-'0');
}else{
return 0;
}
}
result = flag*result;
if(flag==1&&result>(long)Integer.MAX_VALUE) return 0;
if(flag==-1&&result<(long)Integer.MIN_VALUE) return 0;
return (int)result;
}
}