leetcode 解题 String to Integer (atoi)(C&python)
2016-03-22 20:36
731 查看
//此题是easy题,比较简单,主要困难在考虑全输入的各种情况: //1、开始的时候有空格等空白字符 //2、开头有加减号 //3、溢出(第一次写就是没有考虑到这个情况) //C代码 int myAtoi(char* str) { int i=0; double result = 0; int IsNegative = 0; while(isspace(str[i])) { i++; } if(str[i] == '-') { IsNegative = 1; i++; } else if(str[i] == '+') { IsNegative = 0; i++; } else { } for(;i<strlen(str);i++) { if(isdigit(str[i])) { result = result*10 + (str[i] - '0'); } else { break; } } if(IsNegative == 1) { result *= (-1); } if(result > INT_MAX) { result = INT_MAX; } if(result < INT_MIN) { result = INT_MIN; } return (int)result; }
#python代码 class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ num = "1234567890" INT_MAX = 2147483647 INT_MIN = -2147483648 i = 0 sum = 0 flag = 1 str = str.strip() if len(str) == 0: return 0 else: if str[i] == '-': flag = -1 i+= 1 elif str[i] == '+': flag = 1 i+= 1 if i >= len(str): return 0 while i<len(str) and str[i].isdigit(): tempint = int(str[i]) if INT_MAX/10 >= sum: sum = sum*10 else: if flag == 1: return INT_MAX if flag == -1: return INT_MIN if INT_MAX - tempint >= sum: sum += tempint else: if flag == 1: return INT_MAX if flag == -1: return INT_MIN i+=1 return sum*flag
相关文章推荐
- 据廖雪峰python3教程----python学习第五天
- Python下的Mysql模块MySQLdb安装
- python操作sqlalchemy表间关系
- Trick (八)——list 模拟 stack(Python)
- python读入中文txt
- 二分查找
- Python 小记
- python迭代器与生成器
- 如何使Python支持中文注释
- 【python小练】0000
- Python守护进程
- Python笔记3
- Python笔记2
- Python笔记1
- python处理文件效率对比awk
- python之logging模块
- Python 的开始
- Python小工具--删除svn文件
- python基础学习
- python egg