I know this question has been asked before, but the answers were, with my very limited knowledge of C++, too complicated for me to understand. So I'm asking you, how do I convert an integer to a string?
I mean, this is what I found on this forum, and it doesn't make any sense at all to me:
1 2
int number;
string String = static_cast<ostringstream*>( &(ostringstream() << number) )->str();
#include <iostream>
#include <string>
#include <sstream>
template <class T>
std::string ToString( T t )
{
std::stringstream ss;
ss << t;
return ss.str();
}
int main( int argc, char* argv[] )
{
int a = 52;
std::string s = ToString<int>( a );
std::cout << "s is " << s << std::endl;
return 0;
}
Not very simple for me xD There were a lot of things that I didn't understand there, but I guess I'll just have to memorize it and then later on when I know more about C++ I maybe will be able to understand it. What I was going to use it for was solving Euler Problem #4, and I copied the code that I mentioned above without any understanding of it whatsoever. But it still does not seem to work, do you see what's wrong?
Euler Problem #4: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.
Find the largest palindrome made from the product of two 3-digit numbers.
That's not the answer I get when I run my version, though. I should mention that I don't use strings at all.
I have a break coming up (currently at work), I'll see if I can take another look at your code then. If you want me to put mine up, I'd be more than happy to. Just don't want to spoil the game for you. :-)
#include <iostream>
#include <ctime>
bool IsPalindrome( int n )
{
int nCpy = n; // Copy of n
unsignedlong r = 0; // n reverse
while( nCpy > 0 )
{
r = r * 10 + nCpy % 10;
nCpy /= 10;
}
return n == r;
}
int main( int argc, char* argv[] )
{
unsignedlong largest = 0; // Largest palindrome
unsignedint i, j; // Loop counters
unsignedlong p; // Product of i and j
int first, second; // Factors
clock_t t = clock(); // Timer
for( i=100; i < 1000; ++i )
{
for( j=100; j < 1000; ++j )
{
p = i * j;
if( IsPalindrome( p ) )
{
if( p > largest )
{
largest = p;
first = i;
second = j;
}
}
}
}
t = clock() - t;
std::cout << "The largest palindrome is " << largest;
std::cout << " (" << first << " x " << second << ")\n";
std::cout << "Time taken: " << static_cast<float>( t ) / CLOCKS_PER_SEC << " seconds\n";
return 0;
}
Answer I get is 906609 (913*993).
There's some timing stuff in the and it could probably be tweaked to be a little faster, but it's reasonably quick.
I'll still take a look at your current code when I get the chance, if only for sheer curiosity.
Oh! You added test > palindrome because the loop goes through lower three-digit numbers sometimes than those the current palindrome consists of, right? So the last one the loop met was 580085, but not the largest? I get it. Thanks man :)