gpt4 book ai didi

c# - 如何在不使用字符串的情况下创建/读取具有特定小数位的数字?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:51:56 25 4
gpt4 key购买 nike

我正在尝试做以下 SPOJ 问题:

https://www.spoj.com/problems/GUANGGUN/

问题是,我不知道如何正确创建具有特定小数位的数字(例如:如果 4 被输入到控制台,它将创建 1.1111 ,或者在输入 8 的情况下:1.11111111)。我尝试用string来做,但是超过了这个问题的惩罚时限

但即便如此,我也不知道如何在不将其变成字符串并使用 variable[x] 的情况下读取特定位置的小数。

非常感谢任何帮助。

编辑:我输入了以下代码作为解决方案:

using System;
using System.Linq;
using System.Collections;

namespace SPOJG
{
class Program
{
private static long Formula(long n) => 81 * (n / 9) + (n % 9) * (n % 9);
static void Main(string[] args)
{
bool takeInputs = true;

Queue inputs = new Queue();

while (takeInputs)
{
string inputString = Console.ReadLine();

int n;
bool isNumber = int.TryParse(inputString, out n);

if (isNumber)
{
inputs.Enqueue(inputString);
}
else
{
while (inputs.Count > 0)
{
GUANGGUN(Convert.ToInt32(inputs.Dequeue()));
}

takeInputs = false;
}
}
}

static void GUANGGUN(int input)
{
var output = string.Join(Environment.NewLine, Enumerable
.Range(input, 1)
.Select(n => $"{Formula(n),1}"));

Console.WriteLine(output);
}
}
}

但是,SPOJ 表示这是一个错误的答案。有什么想法吗?

最佳答案

您正在尝试解决 XY problem .正如我们在最初的问题中看到的那样

https://www.spoj.com/problems/GUANGGUN/

n最大可达1e18;这就是为什么

11....1 (n times) 

对于蛮力方法来说有点太长了(1e18 digits is a string of 1.7 PetaByte 大小)。其实你在找A080151顺序,代码为

private static long Solution(long n) => 81 * (n / 9) + (n % 9) * (n % 9);

演示:

using System.Linq;

...

var demo = string.Join(Environment.NewLine, Enumerable
.Range(1, 15)
.Select(n => $"{n,2} -> {Solution(n),3}"));

Console.Write(demo);

结果:

 1 ->   1
2 -> 4
3 -> 9
4 -> 16
5 -> 25
6 -> 36
7 -> 49
8 -> 64
9 -> 81 <- Example from the problem
10 -> 82 <- Example from the problem
11 -> 85
12 -> 90
13 -> 97
14 -> 106
15 -> 117

关于c# - 如何在不使用字符串的情况下创建/读取具有特定小数位的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57008951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com