实现atoi

1. 去掉首位空格
2. 判断首位是否有正负号
3. 判断各位是否是0~9,有其他字符直接返回当前结果
 
 1 public class Solution {
 2     public int atoi(String str) {
 3         str = str.trim();
 4         int result = 0;
 5         boolean isPos = true;
 6         
 7         for(int i=0; i<str.length(); i++) {
 8             char c = str.charAt(i);
 9             if(i==0 && (c == '+' || c == '-')) {
10                 isPos = c == '+' ? true : false;
11             } else if(c >= '0' && c <= '9') {
12                 if(result > (Integer.MAX_VALUE- (c-'0'))/10) {
13                     return isPos ? Integer.MAX_VALUE : Integer.MIN_VALUE;
14                 }
15                 result = result * 10 + c - '0';
16             } else {
17                 return isPos ? result : -result;
18             }
19         }
20         
21         return isPos ? result : -result;
22     }
23 }

 

 
 
 
 
posted @ 2017-08-29 20:37  HitAnyKey  阅读(182)  评论(0编辑  收藏  举报