What's Here?
- Members: 244,213
- Replies: 692,966
- Topics: 113,134
- Snippets: 3,863
- Tutorials: 935
- Total Online: 1,478
- Members: 85
- Guests: 1,393
|
Checks if an integer is palindromic (reads the same backwards as it does forwards)
|
Submitted By: gabehabe
|
|
|
Rating:
|
|
Views: 306 |
Language: C++
|
|
Last Modified: October 5, 2008 |
|
Instructions: Note that there are a number of ways to convert an integer directly to a string, but I chose to use stringstream objects. Feel free to modify the code to convert it in a different manner! |
Snippet
/*
* A function to find whether a number is palindromic
* Author: Danny Battison
* Contact: gabehabe@googlemail.com
*/
#include <string>
#include <sstream>
bool numericPalindrome(int x)
{
std::ostringstream strstrm; // create a stringstream (a simple way to add a number to a string)
strstrm << x; // add the number to the stringstream
std::string str = strstrm.str(); // get the stringstream object as a string
for (unsigned int i = 0; i < str.length()-1; i++) // loop through
if (str[i] != str[str.length()-1-i]) // if it reads differently, return false
return false;
// if this point was reached, the number is palindromic
return true;
}
/** EXAMPLE USAGE **/
#include <iostream>
using namespace std;
int main()
{
cout << numericPalindrome(404); // will output 1 (true)
cout << numericPalindrome(23993); // will output 0 (false)
cin.get(); // pause for input
return EXIT_SUCCESS; // successful execution
}
Copy & Paste
|
|
|
Be Social
Reference Sheets
Bye Bye Ads
Monthly Drawing
Top Contributors
Top 10 Kudos This Month
|