Created
January 6, 2016 01:43
-
-
Save ButchDean/d86a079298e78f59649e to your computer and use it in GitHub Desktop.
Demo code inspired by Project Euler to determine if a number is palindromic.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cstdlib> | |
#include <cmath> | |
#include <vector> | |
int main(int argc, char* argv[]) | |
{ | |
if(argc == 1) | |
return 0; | |
const unsigned int NUMDIGITS = (atoi(argv[1]) == 0) ? 1 : (int)log10(abs(atoi(argv[1]))) + 1; | |
const unsigned int NUM = atoi(argv[1]); | |
unsigned int d = 0; | |
double actual, fd, frac; | |
double correction = 1e-9; | |
std::vector<int> digits; | |
printf("Number of digits [%d]\n", NUMDIGITS); | |
actual = NUM / pow(10, NUMDIGITS - 1.0); | |
frac = modf(actual + correction, &fd); | |
printf("(1) Going in with num [%d] and actual [%f] and whole part [%f] and frac [%f]\n", NUM, actual, fd, frac); | |
digits.push_back((int)fd); | |
// Extract remaining digits. | |
for(int i = 1; i < NUMDIGITS; i++) | |
{ | |
actual = frac * 10.0; | |
frac = modf(actual + correction, &fd); | |
printf("(2) Going in with num [%d] and actual [%f] and whole part [%f] and frac [%f]\n", NUM, actual, fd, frac); | |
digits.push_back((int)fd); | |
} | |
// Print individual digits. | |
for(const auto& i : digits) | |
{ | |
printf("%d ", i); | |
} | |
puts("\n"); | |
bool isPalindromicNumber = true; | |
// Check if number is palindromic. | |
for(int j = 0; j < digits.size() / 2; j++) | |
{ | |
printf("%d ", digits[j]); | |
if(digits[j] != digits[digits.size() - 1 - j]) | |
{ | |
isPalindromicNumber = false; | |
break; | |
} | |
} | |
puts("\n"); | |
if(isPalindromicNumber) | |
puts("Number is palindromic\n"); | |
else | |
puts("Number is not palindromic\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment