Trying to continue this function with another for-loop that will remove lagging zeros. I.e if poly a is 1 1 1 and poly b is 0 -1 -1, answer is 100, but should be 1, how can I remove the zeros?
Asked
Active
Viewed 142 times
1
-
Of course, since question is tagged C++, the usual "Don't use dynamic arrays, use `std::vector`" advice applies. – Frerich Raabe Nov 01 '13 at 07:53
-
1Why did you remove code example? Without it this question makes no sense at all – mvp Nov 01 '13 at 07:54
2 Answers
1
If you MUST use a dynamic array, and not a stl vector or array:
//first get the index of the last trailing 0
int j;
for (j=max-1; j>0 && sum[j] == 0; --j);
//next allocate memory for new array that will not have any trailing 0s
int* tmp = sum;
sum = new int[j+1];
//now copy old values into new array
for(size_t k=0;k<=j;++k){
sum[k] = tmp[k];
}
delete[] tmp;
Feel free to replace the loop for copying values with the shorter memcpy
command:
memcpy(sum,tmp,sizeof(int)*(j+1));
The above code will result in an array of at least 1 value, so if you have all 0s, then it will just be 0. Otherwise it will shrink your array to the appropriate size. I did make the assumption that you stored larger values at the front of your array, and the least significant digits at the end.

AndyG
- 39,700
- 8
- 109
- 143
-
it's an array of integers so how would % work? 1 1 1 represeents indices 0 1 2 respectively and the same applies to the 0 -1 -1 – user2809437 Nov 01 '13 at 04:45
-
for the first loop do I just return the j that fits those conditions? – user2809437 Nov 01 '13 at 04:57
-
@user2809437: I'm not entirely sure what you're asking. The first loop sets `j` to the index of the most significant non-zero digit. After that, it's simply a matter of using that index to create a new array that will only hold our non-trailing-0 digits. – AndyG Nov 01 '13 at 04:59
-
-
@user2809437 system dependent. Usually `unsigned int`. Check this out: http://stackoverflow.com/questions/131803/unsigned-int-vs-size-t – AndyG Nov 01 '13 at 05:06
-
Instead of writing your own loop to copy a range of `int` values, you could just use `memcpy` (or, since this is C++, `std::copy`). – Frerich Raabe Nov 01 '13 at 07:56
0
You should iterate through your list backwards.
for( int i=max-1; i>=0; i--) {
//calculate sum
if (sum[i] == 0 && i == max-1 && max > 0) { max--;}
}
p->deg=max;
p->coeffs=sum;

shade4159
- 178
- 2
- 8
-
1I like this solution; simply decrementing `max` so that trailing 0s are hidden. The memory for the trailing 0s is still allocated, though. I think OP should clarify what s/he would like. – AndyG Nov 01 '13 at 05:05