Little C++ Help - convert int to int[]

falconfighter

Member
Oct 10, 2004
46
0
0
One of my projects for class is to write a program to make a number into a palindrome by adding the reverse of a number to it, i.e.
512 +
215
----
727 == palindrome

I am thinking of writing a function to reverse an array, then convert back then add, so something like
int a = 512;
int old[3];
int new[3];
old = inttoarray(a);
for(int loop = 0; loop <length(a); loop++)
{
new[loop] = old[length(a)-loop]
}
return a+arraytoint(new);

the lynchpin is, I have to find a way to convert int to int array and back again, and I have no idea. I've had a look at stringstreams, but I'm trapped in visual C++ 6, and it doesn't seem to work. Any ideas?
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
Have you learned about the % (mod) operator yet? You could leverage it to do the conversion you want.
 

falconfighter

Member
Oct 10, 2004
46
0
0
I knew about it, but I have no idea how it would work in this situation. I think I can do the arraytoint() function, but the inttoarray just mystifies me.
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
Say you want to pick apart "127"

what is the result of 127 % 10?

what is the result of 12 % 10?

what is the result of 1 % 10?

Have you learned about "while" loops yet?
 

sao123

Lifer
May 27, 2002
12,653
205
106
theres two ways to do it....

you could do this...

[5] * 100 + [1] * 10 + [2] * 1 = 512
[2] * 100 + [1] * 10 + [5] * 1 = 215

but then you have to get the 727 back into an array using divide & mod...


OR

it seems easier to me to just create a function

void array_adder(int[size], int[size], int[size+1]);

performs this function:
[5][1][2]
[2][1][5]
=======
[7][2][7]

[2] + [5] = [7]
[1] + [1] = [2]
[5] + [2] = [7]

and it goes right into the array.
The only pitfall is you have to beware of carry overs, but thats not hard to program.
 

itachi

Senior member
Aug 17, 2004
390
0
0
when your assignment is graded, is it going to be compiled in vc6? if not, get a different stl - either stlport or stdcxx. both are a hell of a lot more compliant than the vc6 stl. otherwise, use sprintf/snprintf.

either instance, convert the integer to a string, and swap the digits. the simplest way would be to print the string in reverse order into a seperate string and call atoi.