第十八周(String to Integer (atoi))

第十八周(String to Integer (atoi))

目录:

  • 本周完成题目
  • 主要过程思路
  • 相关代码

一、本周完成题目

本周共完成1道题目,1道Medium。

具体完成题目及难度如下表:

#TitleDifficulty
8String to Integer (atoi)Medium

题目内容

1、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.

题目大意:给定一个字符串,将其转化为整形数字。(注意:需要考虑越界情况,大于边界值IN_MAX或小于IN_MIN需要返回边界值。另外字符串中数字以外的部分不用考虑)

二、主要过程思路

1、String to Integer (atoi):

本题比较简单,核心是读取每个数字然后加入到已读入的数字中。同时已读入的数字乘十。
另外,需要考虑前面的“-”和“+”,如果有的话改变indicator,表示数字是正的或负的。如果发现result的值大于边界值INT_MAX或者小于INT_MIN的时候,返回边界值,停止下面的访问。

三、相关代码

String to Integer (atoi)

class Solution {
public:
    int myAtoi(string str) {
      long result = 0;
      int indicator = 1;
      int i=0;
      i = str.find_first_not_of(' ');
      if(str[i] == '-' || str[i] == '+')
         indicator = (str[i++] == '-')? -1 : 1; 
      while('0'<= str[i] && str[i] <= '9') {
         result = result*10 + (str[i++]-'0');
         if(result*indicator >= INT_MAX) return INT_MAX;
         if(result*indicator <= INT_MIN) return INT_MIN;                
      }
      return result*indicator;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值