# Leetcode 8. String to Integer (atoi) ###### tags: `Leetcode(JAVA)` 題目 : https://leetcode.com/problems/string-to-integer-atoi/ 。 想法 : 很煩的一題,主要可能會出錯的地方: 溢位就輸出最大值、先數字再字母->輸出數字、先字母再數字->不輸出 時間複雜度 : 程式碼 : (JAVA) ``` class Solution { public int myAtoi(String s) { boolean dig=false, negsign=false; long res=0; for(int i=0 ; i < s.length() && res < Integer.MAX_VALUE ; i++){ char ch=s.charAt(i); if(ch == '+' && !dig){ dig=true; } else if(ch == '-' && !dig){ dig=negsign=true; } else if(ch>='0' && ch<='9'){ dig=true; res=res*10+ch-'0'; } else if(!(ch == ' ' && !dig)){ break; } } res *= negsign ? -1 : 1; if(res > Integer.MAX_VALUE) res=Integer.MAX_VALUE; if(res < Integer.MIN_VALUE) res=Integer.MIN_VALUE; return (int)res; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up