Leetcode 8. String to Integer (atoi)( C++版)
来源:互联网 发布:云计算的部署方式 编辑:程序博客网 时间:2024/06/05 06:20
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.
思路分析:
将一个字符串转化为整数。考虑输入情况:
- 输入有空格(若空格在最前面或最后面,忽略空格;若空格在字符中间,比如“ 0012 a34”,返回为空格前面的计算结果,即12);
- 正负数:第一个有效字符为数字或者“+”,是正数。第一个有效字符如果为“-”,是负数。若其他字符为非数字字符,则返回该字符前面的计算结果;
要注意的点:
结果应用long型存储,防止越界。最后转化为int型;
class Solution {public: int myAtoi(string str) { if(str.length() == 0) return 0; long sum = 0; bool isPositive = true;//默认为正数 int i = 0; for( ; i < str.length(); ){//过滤最初的空格或者符号位 if(str[i] == ' '){ i ++; continue; } else if(str[i] == '-'){ isPositive = false; i ++; break; } else if(str[i] == '+'){ i ++; break; } else break;//如果第一个字符为数字,则不做任何动作,进入下面的计算 } for( ; i < str.length(); i ++){ // if(str[i] == ' ' || str[i] == '-' || str[i] == '+' || !isdigit(str[i]) ){//输入不合格 if(!isdigit(str[i]) ){ break; } if(isPositive){ sum = sum * 10 + str[i] - '0'; if(sum >= INT_MAX) return INT_MAX; } else{ sum = sum * 10 - (str[i] - '0'); if(sum <= INT_MIN) return INT_MIN; } } return sum; }};
0 0
- Leetcode 8. String to Integer (atoi)( C++版)
- [C++]LeetCode: 24 String to Integer (atoi)
- 【leetcode c++】08 String to Integer (atoi)
- Leetcode c语言-String to Integer (atoi)
- 【LeetCode算法练习(C++)】String to Integer (atoi)
- [LeetCode]8. String to Integer (atoi)
- LeetCode 8. String to Integer (atoi)
- 8. String to Integer (atoi) Leetcode Python
- 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 OJ> 8. String to Integer (atoi)
- leetCode 8. String to Integer (atoi)
- 8. String to Integer (atoi) LeetCode
- leetcode 8. String to Integer (atoi)
- leetcode 8. String to Integer (atoi)
- LeetCode 155. Min Stack
- 机器学习入门学习笔记:(1)BP神经网络原理推导及程序实现
- Linux实现进度条
- 串的模式匹配算法1——Brute-Force(BF)算法
- 在Storyboard中设置tableview的secsion以及rows
- Leetcode 8. String to Integer (atoi)( C++版)
- 从IO到NIO
- Head First Java第二章
- TCP和UDP的区别
- 作业:c++作业3-项目4
- 安装 oracle
- 55. Jump Game
- 安卓端获取IPV4和MAC地址
- C语言回炉(4)