Leetcode 8. 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.

Link:https://leetcode.com/problems/string-to-integer-atoi/

思路:

1 如果出现字符 -> 则忽略
2 如果溢出overflow,返回最大值、最小值
3 符号位symbol


 public static int MyAtoi(string str)
        {
            if (str == null || str.Length == 0)
                return 0;

            bool isNeg = false;
            str = str.Trim();

            char[] charArray = str.ToCharArray();
            int curIndex = 0;

            //获取整数符号
            if (charArray[0] == '+')
            {
                isNeg = false;
                curIndex++;
            }
            else if (charArray[0] == '-')
            {
                isNeg = true;
                curIndex++;
            }
            else
                isNeg = false;

            //把字符串转换为整数
            Int64 num = 0, absnum = 0;

            char c;
            while (curIndex < str.Length)
            {
                c = charArray[curIndex];
                if (!Char.IsDigit(c))
                    break;
                absnum = 10 * absnum + (c - '0');//c是字符串的asscii

                if (isNeg)
                    num = -absnum;
                else
                    num = absnum;

                //判断是否溢出
                if (num > Int32.MaxValue)
                    return Int32.MaxValue;
                if (num < Int32.MinValue)
                    return Int32.MinValue;

                curIndex++;
            }

            return (int)num;
        }



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值