LeetCode 8 String to Integer (atoi)
来源:互联网 发布:windows无法启动怎么办 编辑:程序博客网 时间:2024/04/30 15:07
题目大意:
对于传入的字符串,将其转换成为对应的整数值,注意有非数字输入时将第一个非数字输入往后的所有输入无视
注意处理开头的空格,无视掉这些空格
然后就是开头可能有正负号
大致思路:
知道了在非法字符之后的串是无视掉的之后不是很难
做这个题顺便回忆了一下long long强制类型转换成为int的时候的过程
由于是强制截断取了long long的后半段的位来当作int,当long long型的某个值不超过int的时候,强制截断得到的数刚好是相同的,但是当这个值超过int范围时,强制转换得到的值是long long表示下后32位截断的值(补码表示)
代码如下:
Result : Accepted Time : 8 ms
class Solution {public: int myAtoi(string str) { if(str.empty()) return 0; bool positive = true; int sz = str.size(); int now = 0; while(now < sz && str[now] == ' ') now++; if(str[now] == '-') positive = false, now++; else if(str[now] == '+') now++; long long ans = 0; if(positive){ while(now < sz && str[now] <= '9' && str[now] >= '0'){ ans = ans*10 + str[now] - '0'; if(ans >= 0x000000007fffffff) ans = 0x000000007fffffff; now++; } return (int)ans; }else{ while(now < sz && str[now] <= '9' && str[now] >= '0'){ ans = ans*10 + str[now] - '0'; if(ans >= 0x0000000080000000) ans = 0x0000000080000000; now++; } return (int)-ans; } }};
0 0
- LeetCode 8 - String to Integer (atoi)
- [LeetCode 8] String to Integer (atoi)
- leetcode 8STRING 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 Java] 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)
- String to Integer (atoi) - LeetCode 8
- C++服务器端+Android客户端的网络通信
- CSS层叠样式表——学习笔记
- C语言深度剖析-----函数
- svn文件回滚到某个历史版本
- React Native-18.React Native 常用API及实践 NetINfo
- LeetCode 8 String to Integer (atoi)
- JAVA实现在excel插入图片(POI模式)
- 主成分分析(Principal components analysis)-最大方差解释
- Exynos4412 Uboot 移植(六)—— 相关知识补充
- iOS mask 层和 CAShapeLayer层中间挖去一部分的 源码分析
- sendmail使用
- B+树索引算法
- 【nodejs】npm常用命令
- LeetCode 278. First Bad Version