gpt4 book ai didi

在任意两个数字基数之间转换的 C# 代码

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:03 26 4
gpt4 key购买 nike

我正在处理 exercism.io 的一个问题,该问题要求函数 s.t.给定一个数字数组、一个指定的输入基数(例如基数 2)和一个输出基数(例如基数 10),该函数的输出将是新基数中相同数字的数字数组。

例如如果输入是 Rebase(2, { 1, 0, 1, 0, 1, 0 }, 10) 输出应该是 {4, 2}

我已经尝试实现这个问题的解决方案,首先将数字重新设置为基数 10,然后根据 this page 上的方法对数字进行重新设置。取余数和除以基数的商来找到数字的位数。

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

public static class AllYourBase
{
public static int[] Rebase(int inputBase, int[] inputDigits, int outputBase)
{
int baseTen = 0;
int remainder;
int quotient;

LinkedList<int> coeffHolder = new LinkedList<int>();
if (outputBase <= 1)
throw new ArgumentException();


if(inputBase <= 1)
throw new ArgumentException();


for(int i = inputDigits.Length-1; i >= 0; i--)
{
baseTen += (int)inputDigits[i] * (int)Math.Pow(inputBase, i);
}

quotient = baseTen;


while(quotient > 0)
{
remainder = quotient % outputBase;
coeffHolder.AddFirst(remainder);
quotient = (int)quotient / (int)outputBase;


}

return coeffHolder.ToArray();
}

}

如上所述,我对 Rebase(2, { 1, 0, 1, 0, 1, 0 }, 10) 的预期输出是 {4, 2} ,但出于某种原因,我得到的答案是 {2, 1}

我不确定为什么我得到的结果只有我预期的一半。

附言我知道有内置方法可以更改基数,但由于这是一个练习,我更倾向于通过我自己的函数实现来转换它。

如有任何帮助,我们将不胜感激!

最佳答案

您正在以相反的顺序(从右到左)处理数字,并在处理过程中(从右到左)减少 2(输入基数)的指数。

这会以 2 的降幂(inputBase)从左到右处理数字。

for (int i = 0; i < inputDigits.Length; i++)
{
int j = inputDigits.Length - (i + 1);
baseTen += (int)inputDigits[i] * (int)Math.Pow(inputBase, j);
}

关于在任意两个数字基数之间转换的 C# 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56841242/

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