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; } }