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.
1. null or empty string 2. white spaces 3. +/- sign 4. calculate real value 5. handle min & max
public class Solution { public int atoi(String str) { // Start typing your Java solution below // DO NOT write main() function if(str==null|| str.length() <1) return 0; str = str.trim(); int i = 0; char flag = '+'; if(str.charAt(0) == '+') i++; else if(str.charAt(0) == '-'){ i++; flag = '-'; } double result = 0; while(str.length()>i && str.charAt(i) >= '0' && str.charAt(i) <='9'){ result = 10* result + (str.charAt(i) - '0'); i++; } if (flag == '-') result = -result; if(result < Integer.MIN_VALUE){ result = Integer.MIN_VALUE; } if(result > Integer.MAX_VALUE){ result = Integer.MAX_VALUE; } return (int)result; } }
mistake:
learned: str.charAt(i) - '0' convert a character in string to a number