原题链接在这里:https://leetcode.com/problems/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.
题解:
先把前后的空格去掉,然后取首个符号位。
Note溢出,若是res已经大于Intger.MAX_VALUE/10, res*10就会溢出,若是res == Integer.MAX_VALUE/10, 但最后一位比8大都会溢出,因为Integer的范围是 -2147483648 到 2147483647, 最后一位若是8的话就会溢出, 因为Integer.MAX_VALUE 的最后一位是7.
Time Complexity: O(str.length()). Space: O(1).
AC Java:
1 public class Solution { 2 public int myAtoi(String str) { 3 if(str == null || str.length() == 0){ 4 return 0; 5 } 6 7 //去掉前后空格 8 str = str.trim(); 9 int i = 0; 10 char flag = '+'; 11 //首个char是符号 12 if(str.charAt(i) == '+'){ 13 i++; 14 }else if(str.charAt(i) == '-'){ 15 flag = '-'; 16 i++; 17 } 18 19 int res = 0; 20 while(i<str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'){ 21 //溢出 22 if(res > Integer.MAX_VALUE/10 || (res == Integer.MAX_VALUE/10 && str.charAt(i)>='8')){ 23 return flag == '+' ? Integer.MAX_VALUE : Integer.MIN_VALUE; 24 } 25 res = res*10 + (str.charAt(i)-'0'); 26 i++; 27 } 28 if(flag == '-'){ 29 res = -res; 30 } 31 return res; 32 } 33 }