2015年9月16日星期三

Leetcode 8 String to Integer (atoi)

Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

Solution 1:  The hard part is to keep res not overflow.
 public class Solution {  
   public int myAtoi(String str) {  
     int n=str.length();  
     int i=0, res=0;  
     boolean pos=true;  
     while (i<n && str.charAt(i)==' ') i++;  
     if (i==n) return 0;  
     if (str.charAt(i)=='+') i++;  
     else if (str.charAt(i)=='-') {  
       i++;  
       pos=false;  
     }  
     if (i==n) return 0;  
     for (;i<n;i++) {  
       int num=str.charAt(i)-'0';  
       if (num>9 || num<0) return res;  
       if (pos) {  
         if (res>(Integer.MAX_VALUE-num)/10) return Integer.MAX_VALUE;  
         else res=res*10+num;  
       }  
       else {  
         if (res<(Integer.MIN_VALUE+num)/10) return Integer.MIN_VALUE;  
         else res=res*10-num;  
       }  
     }  
     return res;  
   }  
 }  

没有评论:

发表评论