leetcode--String to Integer (atoi)

来源:互联网 发布:黑马程序员52期百度云 编辑:程序博客网 时间:2024/05/18 00:15

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. 

思路:题目不是很难,但是有很多特殊输入要考虑

1.数字前面有空格 如s=“    123456”
2.数字前出现了不必要或多于的字符导致数字认证错误,输出0   如s=“   b1234”  ,s=“  ++1233” , s=“ +-1121”
3.数字中出现了不必要的字符,返回字符前的数字 如s=“   12a12” , s=“ 123  123”
4.数字越界 超过了范围(-2147483648--2147483647) 若超过了负数的 输出-2147483648  超过了正数的输出2147483647
[java] view plain copy
  1. public class Solution {  
  2.     public int myAtoi(String str) {  
  3.         char[] arr = str.toCharArray();  
  4.         long sum = 0;//先用long  
  5.         boolean start = true;//是否为开头(忽略空格)  
  6.         boolean flag = false;//正负号是否出现过  
  7.         boolean positive = true;//数字正负  
  8.         for(int i=0;i<arr.length;i++){  
  9.             if(arr[i]>='0'&&arr[i]<='9'){  
  10.                 if(positive&&(sum*10+arr[i]-'0'-Integer.MAX_VALUE)>=0return Integer.MAX_VALUE;//越界输出最大值  
  11.                 if(!positive&&((-(sum*10+arr[i]-'0'))-Integer.MIN_VALUE<=0)){//越界输出最小值                 
  12.                     return Integer.MIN_VALUE;  
  13.                 }  
  14.                 sum = sum*10+arr[i]-'0';  
  15.                 start = false;  
  16.             }else if(arr[i]==' ' && start){//忽略开头的空格  
  17.                 continue;  
  18.             }else if(arr[i]=='+' || arr[i]=='-'){                 
  19.                 start = false;  
  20.                 if(!flag){//没有出现过正负号  
  21.                     flag = true;  
  22.                     if(arr[i]=='-') positive=false;  
  23.                 }  
  24.                 else return 0;//出现过正负号,返回0  
  25.             }else{//除数字,空格,正负号以外,返回之前的数字  
  26.                 return (int) (positive?sum:-sum);  
  27.             }  
  28.         }  
  29.         return (int) (positive?sum:-sum);  
  30.     }  
  31. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/45726773

原创粉丝点击