Implement atoi to convert a string to an integer.java
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.ide
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.ui
时间 O(n) 空间 O(1)this
字符串题通常考查的都是边界条件、特殊状况的处理。因此遇到此题必定要问清楚各类条件下的输入输出应该是什么样的。这里已知的特殊状况有:code
javapublic class Solution { public int myAtoi(String str) { str = str.trim(); int result = 0; boolean isPos = true; for(int i = 0; i < str.length(); i++){ char c = str.charAt(i); if(i==0 && (c=='-'||c=='+')){ isPos = c=='+'?true:false; } else if (c>='0' && c<='9'){ // 检查溢出状况 if(result>(Integer.MAX_VALUE - (c - '0'))/10){ return isPos? Integer.MAX_VALUE : Integer.MIN_VALUE; } result *= 10; result += c - '0'; } else { return isPos?result:-result; } } return isPos?result:-result; } }