leetcode 8. String to Integer (atoi)

class Solution {
public int myAtoi(String str) {
str = str.trim();
String[] sArr = str.split("\\s+");
String s = sArr[0];
int flag = 1;
if(s.length()==0) return 0;
if(s.charAt(0)=='-'){
flag = -1;
s = s.substring(1);
}else if(s.charAt(0)=='+'){
flag = 1;
s = s.substring(1);
}else if(s.charAt(0)>='0' && s.charAt(0)<='9'){
flag = 1;
}else{
return 0;
}
long sum = 0;
for(int i=0;i<s.length();i++){
if(!Character.isDigit(s.charAt(i))){
break;
}
int tmp = (int)(s.charAt(i)-'0');
sum = sum*10+tmp;
if(sum*flag>=Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}else if(sum*flag<=Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
}
sum = sum*flag;
return (int)sum;
}
}


class Solution {
public int myAtoi(String str) {
String s = str.trim();
int flag = 1;
if(s.length()==0) return 0;
if(s.charAt(0)=='-'){
flag = -1;
s = s.substring(1);
}else if(s.charAt(0)=='+'){
flag = 1;
s = s.substring(1);
}
long sum = 0;
for(int i=0;i<s.length();i++){
char tmp = s.charAt(i);
if(!Character.isDigit(tmp)){
break;
}
int tmp1 = (int)(tmp-'0');
sum = sum*10+tmp1;
if(sum*flag>=Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}else if(sum*flag<=Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
}
sum = sum*flag;
return (int)sum;
}
}


©️2019 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客