这是获取数字字符列表并使用它们创建长整数的有效方法吗
Is this a valid way to take a list of digit characters and use them to create a long integer?
这是获取数字字符列表并使用它们创建长整数的有效方法吗?
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
相关文章:
- 如何将argv字符串更改为大数字的长整数
- 涡轮增压C++结果无法与长整数
- 长整数的意外模仿行为
- 有符号长整数的含义
- 如何在 c++ 中解释对长整数的操作
- 垃圾价值通过,同时总结一系列长整数
- 如何从 3 个有序整数创建哈希
- 长整数不适用于 8 的幂C++
- 从文件到短 /长整数读取字节
- C++长整数奇数
- 给定一个n位数的长整数,如何访问其部分
- 将长整数转换为字符数组的最安全方法是什么
- 如何基于许多不同的整数创建多种颜色
- 有没有一种方法可以为非整数创建枚举数据类型
- 使用构造函数c++将一个长整数转换为类对象
- 将一个长字符串除以一个长整数
- 无法从嵌入式Python返回长整数到c++
- 如何得到长整数的两个组成部分
- 如何将长整数和/或无符号整数传递给 MPI 参数
- 这是获取数字字符列表并使用它们创建长整数的有效方法吗