Algorithms —check Happy Number
Published in
1 min readApr 2, 2020
Is this Happy Number?
What is Happy Number? Please refer wiki
Brief: 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.
Solution 1:
class Solution {
public:
bool isHappy(int n) {
int originN = n;
if (originN == 1)
return true;
else if (originN == 4)
return false;
int newN = 0;
while (originN > 0) {
newN += (originN % 10) * (originN % 10);
originN /= 10;
}
return isHappy(newN);
}
};
Solution 2:
class Solution {public:
bool isHappyNumber(int n) {
if (n == 1) return true;
else if (n == 4) return false; int digit = 0;
int sum = 0;
while (n > 0) {
digit = n % 10;
sum += (digit * digit);
n /= 10;
}
return isHappyNumber(sum);
}
};
You can use this tool for test: http://calculatorschool.com
Have fun!