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

标签 c# algorithm

我正在尝试做以下 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/

相关文章:

c# - htmlagilitypack 获取具有内容属性的元标记

c# - 在 C# 中允许用户仅输入某些数字,仅整数?

c++ - 适用于任何输入的施特拉森算法

java - 在java中打印数字数组的所有组合

java - 寻找快速哈希算法

java - 我怎样才能影响 minimax 算法更喜欢立即奖励?

c# - 如何动态运行 C# 项目

c# - 如何通过 SignalR 实现 'Who is typing' 功能?

c# - yield return with try catch,我该如何解决

algorithm - 遍历二叉树