def solve(num_str): MAX, MIN = 65535, -65536 num_str_len = len(num_str) i = 0 while num_str[i] == ' ': i += 1 if i == num_str_len: return 0 is_neg = True if num_str[i] == '-' else False i += 1 ans = 0 is_valid = True while i < num_str_len: if num_str[i] < '0' or num_str[i] > '9': print 'err' is_valid = False break if not is_neg and ans > (MAX - (int(num_str[i]) - int('0'))) / 10: return MAX if is_neg and ans > (-MIN - (int(num_str[i]) - int('0'))) / 10: return MIN ans = ans * 10 + int(num_str[i]) - int('0') i += 1 if is_valid: return ans if not is_neg else -ans return 0 print solve(' -65537fa')