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
public class Solution { public int myAtoi(String str) { char [] arr = str.toCharArray(); long sum = 0 ; boolean start = true ; boolean flag = false ; boolean positive = true ; for ( int i= 0 ;i<arr.length;i++){ if (arr[i]>= '0' &&arr[i]<= '9' ){ if (positive&&(sum* 10 +arr[i]- '0' -Integer.MAX_VALUE)>= 0 ) return Integer.MAX_VALUE; if (!positive&&((-(sum* 10 +arr[i]- '0' ))-Integer.MIN_VALUE<= 0 )){ return Integer.MIN_VALUE; } sum = sum*10 +arr[i]- '0' ; start = false ; }else if (arr[i]== ' ' && start){ continue ; }else if (arr[i]== '+' || arr[i]== '-' ){ start = false ; if (!flag){ flag = true ; if (arr[i]== '-' ) positive= false ; } else return 0 ; }else { return ( int ) (positive?sum:-sum); } } return ( int ) (positive?sum:-sum); } }
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/45726773