天天好味道

没钱没权没户口,靠走靠吼靠小狗
随笔 - 68, 文章 - 1, 评论 - 517, 引用 - 5

导航

<2008年10月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

留言簿(12)

随笔分类

随笔档案

文章档案

我的链接

搜索

最新评论

阅读排行榜

评论排行榜

五行写一个atoi

偶然看到的一道题目,要求输入一个字符串指针,输出这个字符串转换成数值的结果。也就是atoi。
不过题目有个奇怪的要求,函数体少于五行。虽然C可以把所有的代码写到一行,不过估计题目的
意思是希望算法简练吧。还要求有必要的错误处理。如果要考虑正负号,非法字符,空格还是挺麻烦的。

posted on 2007-02-09 16:19 jzhang 阅读(3805) 评论(12)  编辑 收藏

评论

# re: 五行写一个atoi

int cint(char *arr){
int flag = (*arr == '-' ? ++arr, 1 : 0), result = 0;
while (*arr != '\0' && *arr >= '0' && *arr <= '9') result = result * 10 + *arr++ - '0';
return flag ? ~result : result;
}

抛块砖,引点玉……
2007-02-09 16:43 | 林杰杰

# C/C++程序就这德行呀

记得国际上有一个比赛,以程序写得隐晦为目标,最让人看不懂的程序可以得大奖,没有指定编程语言,但提交的作品几乎都是C或C++。

这是C的个性,也是C的悲哀。
2007-02-09 17:49 | linkman

# re 林杰杰:

既然你判断*arr == '-',那么'+也应该判断。
*arr != '\0' 似乎是多余的,你觉得呢?
~result 应当是 -result ,笔误 ^_^
2007-02-10 14:48 | 周星星

# re: 五行写一个atoi

周星星同学说得没错,真是细心。 ^_^值得学习。
2007-02-10 19:43 | 林杰杰

# re: 五行写一个atoi

...要晦涩..那不是很简单麻..写点缓冲区,利用缓冲溢出,在程序里用反汇编出来的机器码做事....不通过其他工具想要看懂..这是人类能做到的事嘛...
2007-08-14 03:19 | Dustman

# re: 五行写一个atoi

int atoi(char *msg)
{
while((*msg&&*msg==' ')||(*msg&&*msg=='+')){msg++;}
.....
}

5行实在没办法搞定
2007-08-14 03:24 | ~~

# re: 五行写一个atoi

long atoi(char *arr)
{
long flag = 0, result = 0;

while(*arr == ' ') arr++;
flag = ((*arr == '-') ? ++arr, 1 : (*arr == '+' ? ++arr, 0 : 0));
while (*arr >= '0' && *arr <= '9') result = result * 10 + (*arr++ - '0');

return flag ? -result : result; 
}
算5行不?
2007-10-09 17:36 | lm

# re: 五行写一个atoi

我写了一个四行的函数,大家看看有问题不
int myatoi(char *s)
{
        int ret = (*s == '-' || *s == '+')? (',' - (*s)) * (*(++s) - '0'):  *s - '0';
        while((*(++s) >= '0') && (*s <= '9'))
                ret = (ret >= 0)? ret * 10 + (*s - '0'): ret * 10 + ('0' - *s);
        return ret;
}
如果按照分号来算行数,其实是3行 :-)
用了一个ascii字符的特性 ',' - '+' == 1      ',' - '-' == -1
2007-10-15 21:18 | TripleX

# re: 五行写一个atoi

TripleX,你的函数在输入字符如“+sda”的情况下就会错误执行。
原因在(*(++s) - '0'):  处的自增操作。
2007-11-19 15:08 | lm

# www.bestshopweb.com

welcome to our web-www.bestshopweb.com.Here,you can find some beautiful UGG shoes,we are certain  that the goods are fine and the price is cheap.we are sure that you will have a happy travel in here.
2008-12-12 09:28 | bestshopweb

# re: 五行写一个atoi

welcome to our web-www.bestshopweb.com.Here,you can find some beautiful UGG shoes,we are certain  that the goods are fine and the price is cheap.we are sure that you will have a happy travel in here.
2008-12-12 21:22 | jiexik

# welcome to our web-www.bestshopweb.com.

welcome to our web-www.beswelcome to our web-www.bestshopweb.com.Here,you can find some beautiful UGG shoes,we are certain  that the goods are fine and the price is cheap.we are sure that you will have a happy travel in here.
tshopweb.
2008-12-12 21:24 | jiexik
标题  
姓名  
主页
验证码 *
内容   
  登录  使用高级评论  Top
[使用Ctrl+Enter键可以直接提交]