leetcode中字符串转化为数字
2016-10-11 21:23
127 查看
8. 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.
fas
大概就是说,我们在字符串的前面可以加入空格,和数字的符号+-,然后数字中间不能有其它字符,代码如下
int myAtoi(char* str) {
if(*str==NULL)
return 0;
int res=0;
int sign=1;
int i=0;
while(isspace(*str)) str++;
if(str[0]=='-'){
sign=-1;
i++;
}
else if(str[0]=='+'){
sign=+1;
i++;
}else{
sign=+1;
}
while(str[i]>='0'&&str[i]<='9'){
if(res>INT_MAX/10||(res==INT_MAX/10&&str[i]-'0'>7)){
if(sign==1) return INT_MAX;
else return INT_MIN;
}
res=10*res+(str[i++]-'0');
}
return sign*res;
}
相关文章推荐
- 16进制字符串转化为数字
- js:字符串类型快速转化成数字类型和数字类型快速转化为字符串类型
- 关于字符串与数字的转化(C语言)
- C++字符串转化为数字的库函数
- 将一个数字字符串转换为数字(支持数字中间夹杂字母,但是受int型的限制,转化的长度很有限),如:"1234" -->1234
- javascript字符串数字转化函数parseInt的奇怪现象
- 将数字字符串人民币转化成大写字符串人民币
- C语言中将数字转化为字符串
- 字符串转化为数字函数
- c/c++ 数字和字符串之间的转化
- 将字符串中的中文(英文)字符串转化为阿拉伯数字
- 将一串数字转化为中文字符串,使用 C# 将数字转换成大写人民币 (例如:用户输入2300,系统就会显示两千三百元 )
- 字符串转化数字算法(C#)
- C语言 字符串转化为数字
- 数字转化成字符串
- 面试题: 十进制INT数字转化为16进制字符串、实现字符串和数字的相互转化
- 用C语言实现将一整型数字转化成为字符串
- Groovy Tip 37 字符串和数字之间的转化
- 整理用Java实现数字转化成字符串左边自动补零方法
- JS将数字转化成指定位数的字符串