如果比较代码战争的编译和MVS2019,则相同的代码的工作方式不同



code wars 的任务

编写一个算法,以点十进制格式标识有效的 IPv4 地址。如果 IP 包含以下内容,则应将其视为有效 四个八位字节,值介于 0 和 255 之间(含 0 和 255(。

函数的输入保证为单个字符串。

示例 有效输入:

1.2.3.4 123.45.67.89 无效输入:

1.2.3 1.2.3.4.5 123.456.78.90 123.045.067.089 请注意,前导零(例如 01.02.03.04(被视为无效。

using System;
using System.Collections.Generic;

//Write an algorithm that will identify valid IPv4 addresses in dot-decimal format.
//IPs should be considered valid if they consist of four octets, with values between 0 and 255, inclusive.
//Input to the function is guaranteed to be a single string.
//Examples
//Valid inputs:
//1.2.3.4
//123.45.67.89
//Invalid inputs:
//1.2.3
//1.2.3.4.5
//123.456.78.90
//123.045.067.089
//Note that leading zeros (e.g. 01.02.03.04) are considered invalid.


namespace IPValidation
{
    class Kata
    {
        static int ipnumber = 0;
        static bool numberChecker(List<char> number)
        {
            string checkNum = null;
            foreach (char symb in number)
            {
                checkNum += symb.ToString();
            }
            try
            {
                byte result = Convert.ToByte(checkNum);
                if (result.ToString() == (checkNum).ToString())
                {
                    ipnumber++;
                    return true;
                }
                else return false;
            }
            catch
            {
                return false;
            }
        }
        public static bool is_valid_IP(string ipAddres)
        {                             
            bool getOut = false;
            ipAddres = ipAddres + '.';
            char[] ipArray = ipAddres.ToCharArray();
            List<char> check = new List<char>();          
            foreach (char symbol in ipArray)
            {
                if (check.Contains('.'))
                    break;
                if (symbol == '.')
                {                    
                    getOut = numberChecker(check);
                    if (!getOut)
                        break;
                    check.Clear();
                }
                else
                check.Add(symbol);                              
            }
            if (getOut == true && ipnumber == 4)
            {
                return true;
            }
            else return false;
        }        
    }
    class Program
    {
        static void Main(string[] args)
        {
            bool num = Kata.is_valid_IP("43.99.196.187");
            Console.WriteLine(num);
            Console.ReadKey();
        }
    }
}

结果将为

但是代码战争测试给了我这样的东西:截图来自代码战争

不知道为什么:(

您的类作为static状态:static int ipnumber = 0;

因此,如果您只测试一个案例,它可能会起作用,但如果其他人运行了多个测试,结果可能会有所不同。

找出问题所在的最简单方法是实际运行与屏幕截图中显示的相同测试用例并对其进行调试。解决方案很可能是摆脱方法中的静态状态。

相关内容

最新更新