I wanted to try STL based approach to solve this problem. Please see below my approach.
I am getting WA with below code. What is that I am missing here?
int main()
{
bool happyNumber = false;
unsigned long long int happyCount = 0;
string numberStr;
std::getline(cin, numberStr);
std::vector<unsigned long long int> numbers;
std::set<unsigned long long int> factors;
do
{
numbers.clear();
numbers.reserve(numberStr.size());
for(unsigned long long int iTh = 0; iTh < numberStr.size(); ++iTh)
{
char temp = numberStr[iTh];
numbers.push_back(atoi(&temp));
}
++happyCount;
unsigned long long int sum = 0;
for(std::vector<unsigned long long int>::iterator itr = numbers.begin(); itr != numbers.end(); ++itr)
{
sum += ((*itr)*(*itr));
}
if(sum != 1)
{
if(factors.find(sum) != factors.end())
{
happyNumber = false;
break;
}
else
{
factors.insert(sum);
stringstream ss;
ss << sum;
numberStr = ss.str();
}
}
else
{
happyNumber = true;
break;
}
}while(1);
if(happyNumber)
{
cout << happyCount;
}
else
{
cout << "-1";
}
return 0;
}
Thanks.