这是获取数字字符列表并使用它们创建长整数的有效方法吗

Is this a valid way to take a list of digit characters and use them to create a long integer?

本文关键字:长整数 创建 有效 方法 获取 数字字符 列表      更新时间:2023-10-16

这是获取数字字符列表并使用它们创建长整数的有效方法吗?

LongInt operator+(const LongInt& x, const LongInt& y)
{
    int xCount = 1;
    long int xValue = 0;
    list<char>::iterator it;
    //x.val is a list<char> that contains the digits needed to create the long int
    for(it = x.val.begin(); it != x.val.end(); it++)
    {
        xValue = xValue + (*it - '0');
        xCount++;
    }
}

xCount的目的是跟踪数字的类型(1、10、100、1000等(。

LongInt是一个自定义类,它有一个名为val的列表。这个方法应该接受两个LongInt对象,将它们的列表转换为LongInts,然后将它们相加。我知道我错过了y对象的代码,但在尝试y之前,我想确保我已经放下了x。

提前感谢!

没有,我在上一个线程中解释了如何做到这一点,只是我对反向迭代器有错误。你必须从头开始,而不是结束。很抱歉造成这种混乱。。这应该足够了:

   list<char> digits;
   digits.push_back('1');
   digits.push_back('2');
   digits.push_back('3');
   long int xValue = 0;
   list<char>::iterator it;
   for(it = digits.begin(); it != digits.end(); it++)
   {
      xValue = xValue * 10 + (*it - '0');
   }

假设列表为{‘1’、‘2’、‘3’}。最初,xvalue为0,然后变为0*10+1,即1。那么它1*10+2=12。最后12*10+3=123。

如果LongInt是一个可以具有任意精度的类,则它不能转换为像long int xValue这样的基元数据类型。

如果要添加两个LongInt,则必须手动添加。逐个字符。例如,如果x="174",y="43",那么您的程序将执行以下操作:

carry = 0;
174
 43
  ^---- 4 + 3 + carry = 7, carry = 0
174
 43
 ^----- 7 + 4 + carry = 1, carry = 1
174
 43
^------ 1 + 0 + carry = 2, carry = 0

根据上面的算法,结果是"217",您应该将其存储在另一个LongInt中并返回。

我是否遗漏了运算符重载(sp?:-(?为什么不忘记xCount,只需:

long xValue = 0;
for(it = x.val.rbegin(); it != x.val.rend(); it++) 
{
  xValue = xValue * 10 + ( *it - '0');
}

xCount与它有什么关系?

无论如何,您都需要将10^提高到xCount的功率(但您不会在任何地方增加它(。xCount可能应该是您的数字长度。if语句应该有==if(xCount == 1),但您不需要区分这一点,因为您可以将第一位乘数视为10^0。

"123" = 1*10^2+2*10^1+2*10^0