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.
需求:字符串转成数字,需要识别正负号
""
=>0
-1
=>-1
+-1
=>0
1234567890123456789012345678901234567890
=>0
"2147483648"
=>2147483647
public int myAtoi(String str) { str = str.trim(); if(null==str || "".equals(str)) return 0; char flag = '+'; int i = 0; if(str.charAt(0)=='+'){ flag = '+'; i++; }else if(str.charAt(0)=='-'){ flag = '-'; i++; } double result = 0.0; if(str.length()>12) return 0; while(str.length()>i && str.charAt(i)>='0' && str.charAt(i)<='9'){ result = result * 10 + (str.charAt(i)-'0'); i++; } if(flag=='-') result = -result; if(result>Integer.MAX_VALUE) result = Integer.MAX_VALUE; if(result<Integer.MIN_VALUE) result = Integer.MIN_VALUE; return (int)result; }