字符串转换成整数 解庞果英雄会的一道简单挑战题

刚闲着没事, 逛了逛csdn, 看到了这道编程挑战题 《字符串转换成整数》 ,要求如下: 

题目详情

输入一个表示整数的字符串,把该字符串转换成整数并输出,例如输入字符串"345",则输出整数345。

请完成函数StrToInt,实现字符串转换成整数的功能。

友情提醒

提交代码之前,请复查下你的程序,比如当给的字符串是如左边图片所示的时候,有考虑到么?

当然,它们各自对应的正确输出如右边图片所示(假定你是在32位系统下,编译环境是VS2008以上)

好久没有做这种题了, 题目要求用java, c,c++ ,c#完成,搞.NET的当然选c#了, 试了试, 下面是我提交的代码, 不指望拿奖了, 因为前面已经有百来人提交了正确的解法 (即挑战成功)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] ar = { "", "1", "+1", "-1", "123", "-123", "010", "+00131204", "-01324000", "2147483647", "-2147483648", "-2147483649", "2147483648", "-2147483648", "abc", "-abc", "1a", "23a8f", "-3924x8fc", "   321", "   -321", "123  456", "123   ", "   -321", "   +4488", "  +  4488", "  +  413", "  ++c", " ++1", " --2", "    -2" };

            foreach (var s in ar)
            {
                Console.WriteLine("{0}->{1}", s, StrToInt(s));
            }

            Console.Read();
        }

        static int StrToInt(string str)
        {
            if (str == null)
            {
                throw new ArgumentException("str can't be null!");
            }

            if (str == "")
            {
                return 0;
            }

            str=str.Trim();

            bool singed = false;
            int index = 0;

            if (str[0] == '-' || str[0] == '+')
            {
                singed = true;
                index = 1;
            }

            int length = str.Length;
            int n = 0;

            while (index < length)
            {
                if (char.IsNumber(str[index]))
                {
                    n = n * 10 + (str[index++] - '0');

                    if (n < 0)
                    {
                        if (singed)
                        {
                            if (str[0] == '+')
                            {
                                return 2147483647;
                            }
                            else
                            {
                                return -2147483648;
                            }
                        }
                        else
                        {
                            return 2147483647;
                        }
                        
                    }
                }
                else
                {
                    break;
                }
            }

            if (singed && str[0] == '-')
            {
                n *= -1;
            }

            return n;
        }
    }
}

好久没写c#了,纯当自娱自乐 消遣 。 。

原文地址:https://www.cnblogs.com/leonwang/p/3121212.html