Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,626 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,994 people online right now. Registration is fast and FREE... Join Now!





Palindromic Integers

Checks if an integer is palindromic (reads the same backwards as it does forwards)

Submitted By: gabehabe
Actions:
Rating:
Views: 168

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


  1. /*
  2. * A function to find whether a number is palindromic
  3. * Author: Danny Battison
  4. * Contact: gabehabe@googlemail.com
  5. */
  6.  
  7. #include <string>
  8. #include <sstream>
  9. bool numericPalindrome(int x)
  10. {
  11.     std::ostringstream strstrm; // create a stringstream (a simple way to add a number to a string)
  12.     strstrm << x; // add the number to the stringstream
  13.     std::string str = strstrm.str(); // get the stringstream object as a string
  14.     for (unsigned int i = 0; i < str.length()-1; i++) // loop through
  15.         if (str[i] != str[str.length()-1-i]) // if it reads differently, return false
  16.             return false;
  17.  
  18.     // if this point was reached, the number is palindromic
  19.     return true;
  20. }
  21. /** EXAMPLE USAGE **/
  22. #include <iostream>
  23. using namespace std;
  24.  
  25. int main()
  26. {
  27.    cout << numericPalindrome(404); // will output 1 (true)
  28.    cout << numericPalindrome(23993); // will output 0 (false)
  29.  
  30.    cin.get(); // pause for input
  31.    return EXIT_SUCCESS; // successful execution
  32. }
  33.  

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.




Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month