码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 8. String to Integer

时间:2016-11-01 01:22:57      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:rem   bsp   sig   public   int   leetcode   turn   break   ++   

        public int MyAtoi(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return 0;
            }
            int sign = 1;
            int i = 0;
            for (; i < str.Length; ++i)
            {
                if (str[i] !=  )
                {
                    break;
                }
            }
            if (str[i] == +)
            {
                sign = 1;
                i++;
            }
            else if (str[i] == -)
            {
                sign = -1;
                i++;
            }

            int digit = 0;
            for (; i < str.Length; ++i)
            {
                if (str[i] < 0 || str[i] > 9)
                {
                    break;
                }
                // overflow
                if (digit * sign > Int32.MaxValue / 10 ||
                    (digit * sign == Int32.MaxValue / 10 && (str[i] - 0) > Int32.MaxValue % 10))
                {
                    return Int32.MaxValue;
                }
                if (digit * sign < Int32.MinValue / 10 ||
                    (digit * sign == Int32.MinValue / 10 && (str[i] - 0) * sign < Int32.MinValue % 10))
                {
                    return Int32.MinValue;
                }

                digit = digit * 10 + (str[i] - 0);
            }

            return digit * sign;
        }

 

LeetCode 8. String to Integer

标签:rem   bsp   sig   public   int   leetcode   turn   break   ++   

原文地址:http://www.cnblogs.com/pengdotnet/p/String-to-Integer.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!