企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
mplement 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. Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition. ~~~ public class Solution { public int myAtoi(String str) { int max = Integer.MAX_VALUE; int min = -Integer.MIN_VALUE; long result = 0; str = str.trim(); int len = str.length(); if (len < 1) return 0; int start = 0; boolean neg = false; if (str.charAt(start) == '-' || str.charAt(start) == '+') { if (str.charAt(start) == '-') neg = true; start++; } for (int i = start; i < len; i++) { char ch = str.charAt(i); if (ch < '0' || ch > '9') break; result = 10 * result + (ch - '0'); if (!neg && result > max) return max; if (neg && -result < min) return min; } if (neg) result = -result; //return result; return (int) result; } } ~~~