标签:style blog color strong os io
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.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
题解:思路很简单,就是要注意的细节很多:
代码如下:
1 public class Solution { 2 public int atoi(String str) { 3 if(str == null || str.length() == 0) 4 return 0; 5 6 str = str.trim(); 7 if(str.length() == 0) 8 return 0; 9 10 int kepeler = 0; 11 boolean isNeg = false; 12 if(str.charAt(kepeler) == ‘-‘){ 13 isNeg = true; 14 kepeler++; 15 } 16 else if(str.charAt(kepeler) == ‘+‘) 17 kepeler++; 18 19 long answer = 0; 20 for(;kepeler < str.length();kepeler++){ 21 if(str.charAt(kepeler) < ‘0‘ || str.charAt(kepeler) > ‘9‘) 22 break; 23 answer = answer*10+str.charAt(kepeler) - ‘0‘; 24 } 25 if(isNeg){ 26 answer *= -1; 27 if(answer < Integer.MIN_VALUE) 28 return Integer.MIN_VALUE; 29 return (int)answer; 30 } 31 else { 32 if(answer > Integer.MAX_VALUE) 33 return Integer.MAX_VALUE; 34 return (int)answer; 35 } 36 } 37 }
【leetcode刷题笔记】String to Integer (atoi),布布扣,bubuko.com
【leetcode刷题笔记】String to Integer (atoi)
标签:style blog color strong os io
原文地址:http://www.cnblogs.com/sunshineatnoon/p/3856426.html