[Leetcode]String to Integer (atoi) 简易实现方法

时间:2014-10-28 08:10:59   收藏:0   阅读:175

刚看到题就想用数组做,发现大多数解也是用数组做的,突然看到一个清新脱俗的解法:

 1 int atoi(const char *str) {
 2 
 3        
 4 
 5         if(*str == \0) return 0;
 6 
 7         int n;
 8 
 9         string s(str);
10 
11         istringstream iss(s);
12 
13         iss>>n;
14 
15         return n;
16 
17     }

代码简洁,核心使用的是istringstream C++串流输入类,该类对象能把字符串对象str读出字符并写入到自定义的各种类型变量中。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!