随笔-60  评论-98  文章-0  trackbacks-0

1 .设计函数 int atoi(char *s)
//atio函数实现,总感觉自己代码太繁琐了,by leetaolion@126.com
//atio转换举例 "123"->123
//atio转换举例 "00123"->123
//atio转换举例 " 0 0123"->123
//atio转换举例 "+123"->123
//atio转换举例 "-123"->-123
//atio转换举例 "(+/-)( /e)00123"->0
//atio转换举例 "e00123"->0


#include "iostream.h"
#include "ctype.h"

int my_atoi(char *s);

int my_atoi(char *s)
{
 int i=0,j;
 while (s[0]=='0'||s[0]==' ')//过滤首部0和空格
 {
  s++;
 };
 if ( !isdigit(s[0]) )   //如果第一位不是数字,则可能是符号位
 {
 switch ( s[0] )
  {
  case '+':
  s++;
  while (s[0]>='0'&&s[0]<='9')
  {
   j=int(s[0]-'0');
   i=i*10+j;
   s++;
  }
  return i;
  break;

  case '-':
  s++;
  while (s[0]>='0'&&s[0]<='9')
  {
   j=int(s[0]-'0');
   i=i*10+j;
   s++;
  }
  return 0-i;
  break;
 
  default:
  return i;
  break; 
  }
 }

  while (s[0]>='0'&&s[0]<='9')
  {
   j=int(s[0]-'0');
   i=i*10+j;
   s++;
  }
  return i;


}

void main( void )
{
 char *s=NULL;
 int i;

 s = "   +123456";
 i = my_atoi( s );
 cout<<i<<endl;

 s = "   0-0123456";
 i = my_atoi( s );
 cout<<i<<endl;

 s = "12345e6";
 i = my_atoi( s );
 cout<<i<<endl;
 
}


 

posted on 2006-09-07 16:12 创建更好的解决方案 阅读(416) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理