Leetcode-8(Java) String to Integer (atoi)
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.
传送门:https://leetcode.com/problems/string-to-integer-atoi/
把字符串转换成整型,注意空格和符号即可。
public class Solution { public int myAtoi(String str) { if(str == null) return 0; str = str.trim();//去掉字符串前面的空格 int len = str.length(); if(len == 0) return 0; char signal = '+'; double res = 0; for(int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if(ch == '-' || ch == '+') { if(i != 0) return 0; else { if(ch == '-') signal = '-'; } } else if(ch >= '0' && ch <= '9') { res = res * 10 + ch - '0'; } else break; } if(signal == '-') res = -res; if(res > Integer.MAX_VALUE) return Integer.MAX_VALUE; else if(res < Integer.MIN_VALUE) return Integer.MIN_VALUE; else return (int)res; } }