刷LeetCode(8)——String to Integer (atoi)
来源:互联网 发布:青岛知豆租赁电话 编辑:程序博客网 时间:2024/06/07 18:16
刷LeetCode(8)——String to Integer (atoi)
Code it now! https://leetcode.com/problems/string-to-integer-atoi/description/
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.
实现如下:这题也比较好做,关键是要考虑挺多东西,我也是提交了好多次才发现有这么多要考虑的地方
如下:
开头的空格
正负符号的处理
溢出处理
非法输入
#include <iostream>#include <string>#include <limits.h> #include <assert.h>using namespace std;class Solution {public: int myAtoi(string& str) { int i = 0,sign = 1; long long ret = 0; const int len = str.length(); if( !len ) { return 0; } while( i < len && isspace( str.at(i) ) ) { i++; } while( i < len ) { if( str.at(i) == '+' ) { i++; sign = 1; continue; } if( str.at(i) == '-' ) { i++; sign = -1; continue; } if( str.at(i) < '0' || str.at(i) > '9' ) { return 0; } ret = ret*10 + sign*(str.at(i++) - '0'); } if( ret > INT_MAX || ret < INT_MIN ){ return 0; } return ret; }};int main(){ string str; while( getline(cin,str) && !str.empty() ) { cout << Solution().myAtoi(str) << endl; } return 0;}
阅读全文
0 0
- 刷LeetCode(8)——String to Integer (atoi)
- LeetCode——String to Integer (atoi)
- LeetCode——String to Integer (atoi)
- String to Integer (atoi) —— Leetcode
- leetcode——String to Integer (atoi)
- LeetCode(8)String to Integer (atoi)
- LeetCode(8)String to Integer (atoi)
- LeetCode (8)String to Integer(atoi)
- LeetCode(8)-- String to Integer(atoi)
- LeetCode—8. String to Integer (atoi)
- 刷题的日常[Leetcode]——8)String to Integer(atoi)
- leetcode——8——String to Integer (atoi)
- LeetCode题解——8 String to Integer (atoi)
- #8 LeetCode——String to Integer (atoi)
- leetcode第8题——*String to Integer (atoi)
- Leetcode Problem.8—String to Integer (atoi)
- <8>——String to Integer (atoi)
- Leetcode刷题记——8. String to Integer (atoi)(字符串转整数)
- MyBatis创建项目(1)
- 1015. 德才论 (25)
- Ubuntu 14.04下Django+MySQL安装部署全过程
- JS 字符替换处理replace/replaceAll
- kotlin允许方法传null值时遇到的问题
- 刷LeetCode(8)——String to Integer (atoi)
- iOS 11 Xcode 9 沙箱账号登录不上 反复弹出登录窗口(亲测 OK)
- redis主从复制搭建
- 数据分析的统计学基础--抽样估计
- Linux服务器中jdk的安装
- python 插入日期数据到Oracle
- (六)TabBarController的简单自定义
- 递归函数——爆内存函数实例
- 微信 小程序 一 变量