https://leetcode.com/problems/string-to-integer-atoi/
看了一下题目,虽然要求比较多,但是写起来基本也就是 if else 判断。不过,在处理溢出的时候会比较麻烦,不能直接使用 C 里面的判别方式,需要进行还原运算才可以:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 
 | class Solution {public int myAtoi(String str) {
 boolean isPositive=true;
 boolean isStart=false;
 int num=0;
 for(char c:str.toCharArray()){
 if(c==32){
 if(!isStart) continue;
 else break;
 }else if(c>=48 && c<=57){
 isStart=true;
 int temp1=num*10;
 int temp2=c-48;
 if(isPositive){
 num=temp1+temp2;
 if(num%10!=temp2 || num<temp2) return Integer.MAX_VALUE;
 }else{
 num=temp1-temp2;
 if(num%10!=-temp2 || num>temp2) return Integer.MIN_VALUE;
 }
 }else if(c=='+' && !isStart){
 isStart=true;
 }else if(c=='-' && !isStart){
 isPositive=false;
 isStart=true;
 }else{
 break;
 }
 }
 return num;
 }
 }
 
 | 
看了一下其他人的答案,貌似也大同小异。