LeetCode 8 8. String to Integer (atoi)

RT
string转 int
题目
https://leetcode.com/problems/string-to-integer-atoi/#/description

char 转 int 是 根据 ascii码, 数字从 48开始

思路是 先从字符串中 获取合法的 数字串
1.去除前后空格
2.判断第一个字符是否为 + - 来判断正负
3.最后计算的时候,还要注意边界 IntMax 是 2147483647 ,IntMin是 2147483648,越界的时候特殊处理就好

 bool isNumber(char c)
        {
            if (c >= 48 && c <= 65)
                return true;
            return false;
        }
        //小写字母  97~122 ,大写之母是  65~90
        public int MyAtoi(string str)
        {
            int ans = 0;
            int numOffset = 48;
            int temp = 1; //判断正负
            List<int> nums = new List<int>();

            //去除字符串前后的空格。。。
            str = str.Trim();

            if(str.Length > 0)
            {
                if (!isNumber(str[0]))
                {
                    if (str[0] == '-' || str[0] == '+')
                        temp = str[0] == '-' ? -1 : 1;
                    else
                        return 0;
                }
            }

            //先找出合法的数字串
            for (int i = 0; i < str.Length; i++)
            {
                if (isNumber(str[i]))
                {

                    int num = (int)(str[i] - numOffset);
                    nums.Add(num);
                }
                else if (i > 0)
                    break;
            }

            //计算数字串
            int max = 2147483647;
            int min = -2147483648;
            for (int i = 0; i < nums.Count;i++ )
            {
                //要注意 边界。。
                if(max - ans < nums[i])
                {
                    ans = temp == -1? min:max;
                    break;

                }
                ans += nums[i] * (int)Math.Pow(10, nums.Count - 1 - i);
            }

            ans *= temp;
            return ans;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值