[LeetCode]String to Integer (atoi)

题目描述:(链接)

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.

解题思路:

题目挺麻烦的,需要考虑很多情况。

复制代码
 1 class Solution {
 2 public:
 3     int myAtoi(string str) {
 4         int len = str.size();
 5         if(len == 0) return 0;
 6         
 7         int sign = 1;
 8         int i = 0;
 9         
10         while (str[i] == ' ') {  
11             i++;  
12         }
13         
14         // 符号
15         if(str[i] == '+' || str[i] == '-') {
16             if(str[i] == '+') {
17                 sign = 1;
18             } else {
19                 sign = -1;
20             }
21             ++i;
22         } 
23         
24         long ans = 0;
25         while(isdigit(str[i])) {
26             ans = ans * 10 + str[i] -'0';
27             if(ans > INT_MAX) {
28                 return sign == 1 ? INT_MAX : INT_MIN;
29             }
30             ++i;
31         }
32         
33         return ans * sign;
34     }
35 };
复制代码

 

posted @   skycore  阅读(128)  评论(0编辑  收藏  举报
编辑推荐:
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
阅读排行:
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
点击右上角即可分享
微信分享提示