Happy Number Solutions in C++
Number 202
Difficulty Easy
Acceptance 50.5%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/happy-number/// Author : Hao Chen// Date : 2015-06-08#include <stdlib.h>#include <iostream>#include <map>using namespace std;int squares(int n) {int result = 0;int sq = 0;for (; n>0; n/=10) {sq = n%10;result += (sq * sq);}return result;}bool isHappy(int n) {if (n==1) return true;map<int, bool> m;m[n]=true;while (n!=1) {n = squares(n);//cout << n << endl;if (m.find(n) != m.end()){return false;}m[n] = true;}return true;}int main(int argc, char** argv){int n = 2;if (argc > 1){n = atoi(argv[1]);}cout << n << (isHappy(n) ? " is " : " isn't ") << "a happy number" << endl;return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/happy-number//// Author : liuyubobobo/// Time : 2017-01-18#include <iostream>#include <unordered_set>using namespace std;/// Using HashTable/// Time Complexity: O(logn)/// Space Complexity: O(logn)class Solution {public:bool isHappy(int n) {unordered_set<int> record;record.insert(n);while(n != 1){n = op(n);if( record.find(n) == record.end() )record.insert(n);elsereturn false;}return true;}private:int op(int x){int res = 0;while(x){int t = x % 10;res += t * t;x /= 10;}return res;}};void print_bool(bool res){cout << (res ? "True" : "False") << endl;}int main() {print_bool(Solution().isHappy(19));// truereturn 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/happy-number//// Author : liuyubobobo/// Time : 2020-04-03#include <iostream>using namespace std;/// Floyd's Cycle-Finding Algorithm/// Time Complexity: O(logn)/// Space Complexity: O(1)class Solution {public:bool isHappy(int n) {if(n == 1) return true;int slow = op(n); if(slow == 1) return true;int fast =op(slow); if(fast == 1) return true;while(slow != fast){slow = op(slow);fast = op(fast); if(fast == 1) return true;fast = op(fast); if(fast == 1) return true;}return false;}private:int op(int x){int res = 0;while(x){int t = x % 10;res += t * t;x /= 10;}return res;}};void print_bool(bool res){cout << (res ? "True" : "False") << endl;}int main() {print_bool(Solution().isHappy(19));// truereturn 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/happy-number//// Author : liuyubobobo/// Time : 2020-04-03#include <iostream>#include <set>using namespace std;/// The only cycle is 4-16-37-58-89-145-42-20-4/// Time Complexity: O(logn)/// Space Complexity: O(1)class Solution {public:bool isHappy(int n) {set<int> cycle = {4, 16, 37, 58, 89, 145, 42, 20};while(n != 1){if(cycle.count(n)) return false;n = op(n);}return true;}private:int op(int x){int res = 0;while(x){int t = x % 10;res += t * t;x /= 10;}return res;}};void print_bool(bool res){cout << (res ? "True" : "False") << endl;}int main() {print_bool(Solution().isHappy(19));// truereturn 0;}