Last active
August 29, 2015 14:11
-
-
Save cengiz-io/38c44d5ecd4a041ca087 to your computer and use it in GitHub Desktop.
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 <iostream> | |
#include <sstream> | |
#include <fstream> | |
#include <vector> | |
#include <numeric> | |
#ifndef __APPLE__ | |
#include <algorithm> | |
#endif | |
#define to_string(x) dynamic_cast<ostringstream &>\ | |
((ostringstream() << dec << x)).str() | |
using namespace std; | |
void square(int& i) { | |
i = i * i; | |
} | |
void square_digits(vector<int>& digits) { | |
for_each(digits.begin(), digits.end(), &square); | |
} | |
unsigned int get_new_number(vector<int>& digits) { | |
return accumulate(digits.begin(), digits.end(), 0); | |
} | |
void replace_digits(vector<int>& digits, const int& number) { | |
digits.clear(); | |
string digits_str = to_string(number); | |
for (size_t x = 0; x < digits_str.length(); x++) { | |
digits.push_back(static_cast<int>(digits_str[x] - '0')); | |
} | |
} | |
int is_happy_number(const int& number) { | |
vector<int> digits; | |
replace_digits(digits, number); | |
square_digits(digits); | |
while (1) { | |
unsigned int new_number = get_new_number(digits); | |
if (new_number == 4) return 0; | |
if (new_number == 1) return 1; | |
replace_digits(digits, new_number); | |
square_digits(digits); | |
} | |
} | |
int main(int argc, char *argv[]) { | |
if (argc < 2) return -1; | |
ifstream datafile(argv[1]); | |
string line; | |
while (getline(datafile, line)) { | |
if (line.length() < 1) continue; | |
int number; | |
istringstream number_str(line); | |
number_str >> number; | |
cout << is_happy_number(number) << endl; | |
} | |
} |
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
1 | |
7 | |
22 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment