(Hackerrank 您所在的位置:网站首页 std::string转换为int (Hackerrank

(Hackerrank

2023-04-05 23:44| 来源: 网络整理| 查看: 265

我想我明白为什么你会感到困惑。如果您访问该站点,并选择用 C# 编写答案,您将获得以下模板:

using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text.RegularExpressions; using System.Text; using System; class Solution { // Complete the fairRations function below. static int fairRations(int[] B) { } static void Main(string[] args) { TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true); int N = Convert.ToInt32(Console.ReadLine()); int[] B = Array.ConvertAll(Console.ReadLine().Split(' '), BTemp => Convert.ToInt32(BTemp)) ; int result = fairRations(B); textWriter.WriteLine(result); textWriter.Flush(); textWriter.Close(); } }

但其中一项要求指出:

如果无法执行此操作,请打印NO。

说明书上说:

// Complete the fairRations function below.

这是一个糟糕的模板,如果解决方案不可行,该函数还需要处理打印NO 的附加条件。

您必须修改fairRations 函数的签名,以处理无法解决的情况。您还可以修改Main 中的代码,这显然不足以满足挑战的要求。

如果您需要在输出中写入 int result 以外的其他内容,则需要进行不同的 textWriter.WriteLine 调用以输出字符串。

我强烈推荐在 int.TryParse 或 Dictionary;TKey,TValue;.TryGetValue 等函数中使用的模式。该模式基于以下两个原则:

返回一个布尔值来表示成功/失败。 通过输出参数传递成功案例的负载(在本例中为整数)。

像这样修改fairRations函数:

static bool fairRations(int[] B, out int result) { if (/* TODO: it is possible? */) { result = /* TODO: whatever the result is */; return true; } else { result = 0; return false; } }

你可能想修改Main中的调用如下:

改变...

int result = fairRations(B); textWriter.WriteLine(result);

到...

if (fairRations(B, out int result)) { textWriter.WriteLine(result); } else { textWriter.WriteLine("NO"); }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有