Leetcode 8. String to Integer (atoi) (Easy) (cpp)
2016-07-13 11:34
429 查看
Leetcode 8. String to Integer (atoi) (Easy) (cpp)
Tag: Math, String
Difficulty: Easy
Tag: Math, String
Difficulty: Easy
/* 8. String to Integer (atoi) (Easy) 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. */ class Solution { public: int myAtoi(string str) { if (str.empty()) return 0; long long num = 0; int i = 0, sign = 1; for (; str[i] == ' '; i++) { } if (str[i] == '-' || str[i] == '+') sign = 1 - 2 * (str[i++] == '-'); for(int j = i; j < str.length(); j++) { if(str[j] >= '0' && str[j] <= '9') { num = num * 10 + (str[j]-'0'); if(num > INT_MAX) return sign > 0 ? INT_MAX : INT_MIN; } else break; } return (int)num * sign; } };
相关文章推荐
- 不调用C/C++的字符串库函数,请编写函数strcpy
- 338. Counting Bits
- NOIP2015提高组 信息传递(图论)
- 在亚马逊开店的注意事项—跨海汇
- 七牛qiniu c/c++ sdk 在windows系统环境下使用vs导入lib静态库的使用教程总结
- C 语言笔记;变量初始化
- hdu 2473 帮派
- c++string的erase方法
- C语言判断当前某一个进程是否存在
- C语言获取当前登陆的用户名的UID
- C语言获取当前登陆的用户名
- C++ STL标准模板库(vector)
- C++Primer(5th)学习-数组篇
- 关于c++ 学习
- 求5阶矩阵其对角线上所有元素之和
- inf & nan
- C++中typename和class的区别
- <<More Effective C++>>读书笔记1: 基础议题
- C++建立及销毁链表
- c++多态