Is this a valid way to take a list of digit characters and use them to create a long integer?
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 = xV开发者_开发问答alue + (*it - '0');
xCount++;
}
}
The purpose of xCount is to keep track of the type of number it is (1's, 10's, 100's, 1000's, etc).
LongInt is a custom class which has a list called val. This method is supposed to take the two LongInt objects, convert their list to Long Ints, then add them together. I know I'm missing the code for the y object but I wanted to make sure I have the x down before I try for y.
Thanks in advance!
No, and I explained how to do it in your previous thread, except that I was wrong with the reverse iterator. You have to start from the beginning not the end. Sorry about that confusion.. This should be enough:
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');
}
Let's say the list is {'1','2', '3'}. Initially xvalue is 0, then it becomes 0*10+1, which is 1. Then it 1*10 + 2 = 12. Last 12 * 10 + 3 = 123.
If LongInt
is a class that can have arbitrary precision, it can't be converted to primitive data type like long int xValue
.
If you want to add two LongInt
s, then you've to do it manually. Character by characer. For example, if x = "174", y = "43", then you're program will do the following:
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
From the algorithm above, the result is "217", which you should store in another LongInt
and return that.
Am I missing something about operator overloading (sp? :-) ? Why not just forget about xCount and just:
long xValue = 0;
for(it = x.val.rbegin(); it != x.val.rend(); it++)
{
xValue = xValue * 10 + ( *it - '0');
}
What does xCount have to do with it?
You need to be taking 10^ to the xCount power, anyway (but you don't increment it anywhere). xCount should probably be the length of your number. The if statement should have ==
and be if(xCount == 1)
, but you don't need to distinguish that, because you can consider the first digit multiplier as 10^0.
"123" = 1*10^2+2*10^1+2*10^0
精彩评论