Background:
This problem comes from leetcode.com
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
Question:
I thought of doing a recursion for this particular problem to keep repeating the squaring of the integers until we arrive at 1. I am new with recursion (just read Absolute C++ Ch 13 --- Recursion yesterday).I thought I would give this problem a shot but I am having some trouble.
When I call my function I created I should get a return of 19 since 19 is a "Happy Number", but instead my function just returns 0, and I am not sure why. I just need some help with my approach I have taken and suggestions to changes in my code.
Here is my code:
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int Happy(int n) {
vector<int> nums;
int length = to_string(n).length();
for(int i = 0; i < length; i++) {
int digit = n % 10;
n /= 10;
nums.push_back(digit);
}
reverse(nums.begin(), nums.end());
int sum = 0;
for(int i = 0; i < length; i++) {
sum += pow(nums[i],2);
}
if (sum == 1) {
return n;
}
else {
return Happy(sum);
}
}
int main() {
int n = 19;
int result = Happy(n);
cout << result << endl;
return 0;
}
Again, I am not sure why I get 0 as the result, when it should return 19.