gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:35:10 27 4
gpt4 key购买 nike

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

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 对象,将它们的列表转换为 Long Int,然后将它们相加。我知道我遗漏了 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。

关于c++ - 这是获取数字字符列表并使用它们创建长整数的有效方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5572658/

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