8. String to Integer (atoi)
来源:互联网 发布:mtv合成机软件下载 编辑:程序博客网 时间:2024/06/06 00:36
这道题要把字符串转换成整数,这道题有点繁琐吧,要考虑前面的空格,还有加减号,还有转换的时候超出int的范围,其他的没什么。
#include<stdio.h>#include<ctype.h>int myAtoi(char* str) { int i,temp=0,j=0; while(str[j]==' ') j++; if(!isdigit(str[j])&&!isdigit(str[j+1])) return 0; else if('-'==str[j]) { for(i=j+1;str[i];i++) { if(!isdigit(str[i])) break; if(temp>214748364||(temp==214748364&&str[i]>'8')) { temp=2147483648; break; } temp=temp*10+str[i]-'0'; } temp=-temp; } else if('+'==str[j]) { for(i=j+1;str[i];i++) { if(!isdigit(str[i])) break; if(temp>214748364||(temp==214748364&&str[i]>'7')) { temp=2147483647; break; } temp=temp*10+str[i]-'0'; } } else { for(i=j;str[i];i++) { if(!isdigit(str[i])) break; if(temp>214748364||(temp==214748364&&str[i]>'7')) { temp=2147483647; break; } temp=temp*10+str[i]-'0'; } } return temp;}main(){ char s[10]; scanf("%s",s); printf("%d\n",myAtoi(s));}
简化版:
class Solution {public: int myAtoi(string str) { int i=0; double temp=0; int flag=1; while(str[i]==' ') i++; if(!isdigit(str[i])&&!isdigit(str[i+1])) return 0; if(str[i] == '-' || str[i] == '+') flag = (str[i++] == '-')? -1 : 1; for(;str[i];i++) { if(!isdigit(str[i])) break; temp=temp*10+str[i]-'0'; } temp=flag*temp; if(temp>INT_MAX) temp=INT_MAX; if(temp<INT_MIN) temp=INT_MIN; return temp; }};
0 0
- 8.String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8.String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 序列化和反序列化
- <meta name="viewport" content="width=device-width,initial-scale=1.0">
- DSP+Linux开发技术分析
- 详解SESSION与COOKIE的区别
- 有道内推笔试
- 8. String to Integer (atoi)
- 多级下拉菜单
- js中基本类型与引用类型
- android中.this与.class使用的区别
- 图片查看器
- ACdream 1020 The Game about KILL【约瑟夫环】
- 三五班毕业查询
- POJ Babelfish 2503(map,字典树)
- AppDelegate中几个常用的回调调用时机