public int atoi(String str) {
		long num = 0;
		str = str.trim(); // discards the whitespace at beginning and ends
        if (str.isEmpty()) return 0; // if str is empty or only contains whitespace

        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("[-+]?\\d+.*");
        java.util.regex.Matcher matcher = pattern.matcher(str);
		int flag = 1;
		int i = 0;
		
		if (matcher.matches()){
			if (str.charAt(0)=='-'){ // if str starts with -
				flag = -1;
				i = 1;
			}
			else if (str.charAt(0)=='+'){ // if str starts with +
				flag = 1;
				i = 1;
			}
			
			// main loop
			while (i<str.length()&&(java.lang.Character.isDigit(str.charAt(i)))){
				num = num*10 + Long.valueOf(String.valueOf(str.charAt(i)))*flag;
				i++;
				if (num > Integer.MAX_VALUE){
						num = Integer.MAX_VALUE;
						return (int) num;
				}
				else if (num < Integer.MIN_VALUE){
						num = Integer.MIN_VALUE;
						return (int) num;
				}
			}
		}
		return (int) num;
    }